場景:在定義wpf 用戶控件的時候,希望使用時設置自定義的屬性來改變用戶控件里的狀態或內容等。
下面直接上實例代碼:
用戶控件的后台代碼,定義依賴屬性
public partial class MyUserControl : UserControl
{
public MyUserControl() { InitializeComponent(); } public string MyProperty { get { return (string)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata("")); } }
Xaml 代碼中綁定依賴屬性
<UserControl x:Class="WPFTest.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:myCtl="clr-namespace:WPFTest" d:DesignHeight="300" d:DesignWidth="300" mc:Ignorable="d"> <StackPanel> <TextBlock Text="{Binding RelativeSource={RelativeSource Mode= FindAncestor, AncestorType={x:Type myCtl:MyUserControl}}, Path=MyProperty}" /> </StackPanel> </UserControl>
下面是自定義控件的使用實例:
<Window x:Class="WPFTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WPFTest="clr-namespace:WPFTest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="MainWindow" Width="525" Height="350" mc:Ignorable="d"> <Grid> <WPFTest:MyUserControl MyProperty="ddd" /> </Grid> </Window>
希望對大家有用!
