ViewModel中通过附加属性的改变回调可以获得依赖对象控件
通过后代DataContext中的属性绑定到控件的附加属性上触发附加属性回调以获得控件。
数据上下文类
1 2 3 4 5 6 7 8 9 10 11 12
| public class DataContext:INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _text; public string Text{ get{return _text;} set{ _text = value; PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("Text")); } } }
|
依赖属性类(可置于任何地方)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| namespace MyProperty { public static class MessageInfo { public static readonly DependencyProperty MessageInfoProperty = DependencyProperty.RegisterAttached( "MessageInfo", typeof(string), typeof(MessageInfo), new PropertyMetadata(new PropertyChangedCallback(MessageInfoChanged))); private static void MessageInfoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var box = d as System.Windows.Controls.TextBox; if (null != box) { box.Text = e.NewValue as string; box.ScrollToEnd(); } } public static void SetMessageInfo(System.Windows.Controls.TextBox target, string value) { } } }
|
前台XAML代码
绑定的text 常规绑定
1 2 3
| xmlns:xc="MyProperty"
<TextBox xc:MessageInfo.MessageInfo="{Binding Text}"/>
|