欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF 自定义控件中依赖属性的简单使用

程序员文章站 2022-01-05 10:50:01
...

WPF 自定义控件中依赖属性的简单使用

一、首先添加一个简单自定义控件UserTestControl;
xaml代码如下,将背景色绑定依赖属性:

<UserControl x:Class="WpfApp1.UserTestControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="20" d:DesignWidth="100">
    <Grid>
        <TextBlock Background="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=MyColor}" Text="hello everyone!"></TextBlock>
    </Grid>
</UserControl>

用户控件的后台代码,添加了一个依赖属性MyColor:

namespace WpfApp1
{
    /// <summary>
    /// UserTestControl.xaml 的交互逻辑
    /// </summary>
    public partial class UserTestControl : UserControl
    {
        public UserTestControl()
        {
            InitializeComponent();
        }

        public string MyColor
        {
            get { return (string)GetValue(MyColorProperty); }
            set { SetValue(MyColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyColorProperty =
            DependencyProperty.Register("MyColor", typeof(string), typeof(UserTestControl), new PropertyMetadata("Red"));
    }
}

备注:依赖属性也可在后台绑定:

inding bind = new Binding("MyColor");
bind.Source = this;
text block1.SetBinding(TextBlock.BackgroundProperty, bind);

二、在主程序中使用:

<Window x:Class="WpfApp1.MainWindow"
        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:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="200">
    <Grid>
        <StackPanel>        
            <TextBox Name="tbColor"></TextBox>
            <local:UserTestControl x:Name="usercontrol"></local:UserTestControl>
        </StackPanel>
    </Grid>
</Window>

这样就可以在主程序后台通过用户控件的依赖属性修改用户控件的背景色了:

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            usercontrol.MyColor = "Green";
        }
    }
}

运行效果:
WPF 自定义控件中依赖属性的简单使用
WPF 自定义控件中依赖属性的简单使用

相关标签: WPF