WPF之ViewModel中获得依赖对象控件

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)
{
//target.SetValue(MessageInfoProperty, value);
}
}
}

前台XAML代码

绑定的text 常规绑定

1
2
3
xmlns:xc="MyProperty"

<TextBox xc:MessageInfo.MessageInfo="{Binding Text}"/>