依存関係プロパティによるバインディング
依存関係プロパティ(Dependency Property)を理解できませんが、以下のようにするとバインディングと同様になります。
1.XAML
- スタックパネルに1つのボタンと3つの TextBox を配置します。
- TextBox tb1,tb2,tb3 のうち、tb1 と tb3 に、依存関係プロパティ dp1,dp3 をそれぞれバインドします。
- tb1 に入力をして、ボタンを押すと、tb2、tb3に同じ内容が表示されると言うもくろみです。
- <Window x:Class="WpfApplication7.Window1"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- x:Name="N_1"
- Title="Window1" Height="300" Width="300" >
- <Grid>
- <StackPanel>
- <Button Content="Button" Click="Button_Click"/>
- <TextBox x:Name="tb1" Width="60"
- Text="{Binding ElementName=N_1, Path=dp1}"/>
- <TextBox x:Name="tb2" Width="60"/>
- <TextBox x:Name="tb3" Width="60"
- Text="{Binding ElementName=N_1, Path=dp3}"/>
- </StackPanel>
- </Grid>
- </Window>
2.CS(ビハインドコード)
- 依存関係プロパティ dp1,dp3 を宣言します。
- 最初の TextBox tb1に入力して、ボタンが押すと、3つの TextBox 表示が同じになります。
- tb1への入力が自動的にdp1に反映し、dp3への代入がtb3の表示に自動的に反映します。
- public partial class Window1 : Window
- {
- public Window1()
- {
- InitializeComponent();
- }
- //依存関係プロパティ1
- public string dp1
- {
- get { return (string)GetValue(dp1Property); }
- set { SetValue(dp1Property, value); }
- }
- public static readonly DependencyProperty dp1Property
- = DependencyProperty.Register("dp1", typeof(string), typeof(Window1));
- //依存関係プロパティ3
- public string dp3
- {
- get { return (string)GetValue(dp3Property); }
- set { SetValue(dp3Property, value); }
- }
- public static readonly DependencyProperty dp3Property
- = DependencyProperty.Register("dp3", typeof(string), typeof(Window1));
- //ボタン押下
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- tb2.Text = dp1; //TextBoxのTextに代入
- dp3 = dp1; //依存関係プロパティに代入
- }
- }
3.タイマで参照すると
タイマで、ボタン押下のときと同じ処理をして見ました。
この場合は、tb1の入力は、nullのままで、反映されません。
これは少し意外です。このタイマは、Dispacher 経由のもので、同じスレッドで動作します。これでも同期を取る仕組みをパスしてしまうようです。
- System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
- private void Grid_Loaded(object sender, RoutedEventArgs e)
- {
- timer.Tick += new EventHandler(timer_Tick);
- timer.Interval = new TimeSpan(0, 0, 5);
- timer.Start();
- }
- void timer_Tick(object sender, EventArgs e)
- {
- tb2.Text = dp1; //TextBoxのTextに代入
- dp3 = dp1; //依存関係プロパティに代入
- }
|