数据绑定模式共有四种:OneTime、OneWay、OneWayToSource和TwoWay,默认是TwoWay。
TwoWay 当发生更改时的目标属性或源属性更新目标属性。
OneWay 仅当源属性更改时,请更新目标属性。
OneTime 仅当应用程序启动时或时,请更新目标属性DataContext发生了更改。
OneWayToSource 目标属性更改时,请更新源属性。
- 实现INotifyPropertyChanged并通过OnPropertyChanged主动更新绑定的控件
public class BindEx : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected internal virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
- 构造model
public class testModel : BindEx
{
private string _test="";
public string test
{
get
{
return _test;
}
set
{
_test = value;
OnPropertyChanged("test");
}
}
}
- 绑定数据
<TextBox Text="{Binding test}"/>
model = new testModel
{
test = "test"
};
this.DataContext = model;
- 后台绑定样式
//后台设置绑定的资源
control.style=Resources["MyButton"] as style
- 绑定指定类型数据
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<cvt:EqualVisibilityConverter x:Key="equalVisibilityConverter"/>
<Image.Visibility>
<Binding Path="IsEnable" Converter="{StaticResource equalVisibilityConverter}">
<Binding.ConverterParameter>
<sys:Boolean>true</sys:Boolean>
</Binding.ConverterParameter>
</Binding>
</Image.Visibility>
6.触发自定义事件 模拟点击
Button btn=new Button();
btn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, btn));
Image img = new Image();
img.RaiseEvent(new RoutedEventArgs(Image.MouseLeftButtonDownEvent, img));
- 按钮禁用时显示tooltip
ToolTipService.ShowOnDisabled="True"
留待后查,同时方便他人