WPF使用自定义、用户控件通过依赖属性使用Binding

2023-12-24 23:38:43

比如这里的自定义控件是对TextBox进行包装

UserControl中:

xaml:

<TextBox Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, UpdateSourceTrigger=PropertyChanged}"/>

? ? ? ? --这里就只是简单地绑定上了自己code_behind里面的属性Text,还加上了一个实时更新

code_hehind:

????????

public partial class UserControl1 : UserControl
{

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(
            "Text", 
            typeof(string), 
            typeof(UserControl1), 
            new PropertyMetadata("Hello", new PropertyChangedCallback(OnTextChanged)));

    /// <summary>
    /// 属性值修改就触发这个回调
    /// </summary>
    /// <param name="d"></param>
    /// <param name="e"></param>
    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        
    }

    public UserControl1()
    {
        InitializeComponent();
    }
}

? ? ? ? --code_behind里面有个属性,有个依赖属性,还有一个依赖属性回调

? ? ? ? ---为什么使用依赖属性呢?需要这样子才能在引用这个自定义控件后实现对该自定义控件的绑定,更好地使用MVVM

使用自定义控件UserControl的页面中:

<v:UserControl1 Grid.Row="1" Text="{Binding Value}"></v:UserControl1>

? ? ? ? --这个v就是自定义控件的命名空间,Text绑定的就是ViewModel中的属性

文章来源:https://blog.csdn.net/weixin_46407807/article/details/135188207
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。