數據綁定(二)把控件作為Binding源
阿新 • • 發佈:2018-05-24
slider ide AR title C# mod 變化 pda new 原文:數據綁定(二)把控件作為Binding源
效果如下:
下面的代碼把一個TextBox的Text屬性關聯在了Slider的Value屬性上
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="244" Width="412"> <StackPanel> <TextBox x:Name="textBox1" Text="{Binding ElementName=slider1, Path=Value}"></TextBox> <Slider x:Name="slider1" Maximum="100" Minimum="0"></Slider> </StackPanel> </Window>
效果如下:
當拖動進度條時,TextBox中的內容就會發生變化
與之對應的C#代碼是:textBox1.SetBinding(TextBox.TextProperty, new Binding("Value") {ElementName="slider1"});
控制Binding數據流向的屬性是Mode,他的類型是BindingMode枚舉,可取值為OneWay、TwoWay、oneTime、OneWayToSource,UpdateSourceTrigger屬性用於控制在什麽時候觸發屬性變化,類型是UpdateSourceTrigger枚舉,可取值為PropertyChanged、LostFocus、Explicit和Default。修改源代碼後,當TextBox中的內容發生變化時,拖動條的位置也發生變化了,修改後的代碼:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="244" Width="412"> <StackPanel> <TextBox x:Name="textBox1" Text="{Binding ElementName=slider1, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox> <Slider x:Name="slider1" Maximum="100" Minimum="0"></Slider> </StackPanel> </Window>
數據綁定(二)把控件作為Binding源