mikeo_410


 依存関係プロパティによるバインディング

  依存関係プロパティ(Dependency Property)を理解できませんが、以下のようにするとバインディングと同様になります。

1.XAML

  1. スタックパネルに1つのボタンと3つの TextBox を配置します。
  2. TextBox tb1,tb2,tb3 のうち、tb1 と tb3 に、依存関係プロパティ dp1,dp3 をそれぞれバインドします。
  3. tb1 に入力をして、ボタンを押すと、tb2、tb3に同じ内容が表示されると言うもくろみです。
  1. <Window x:Class="WpfApplication7.Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     x:Name="N_1"
  5.     Title="Window1" Height="300" Width="300" >
  6.     <Grid>
  7.         <StackPanel>
  8.             <Button Content="Button" Click="Button_Click"/>
  9.             <TextBox x:Name="tb1" Width="60" 
  10.                      Text="{Binding ElementName=N_1, Path=dp1}"/>
  11.             <TextBox x:Name="tb2" Width="60"/>
  12.             <TextBox x:Name="tb3" Width="60"
  13.                      Text="{Binding ElementName=N_1, Path=dp3}"/>
  14.         </StackPanel>        
  15.     </Grid>
  16. </Window>

2.CS(ビハインドコード)

  1. 依存関係プロパティ dp1,dp3 を宣言します。
  2. 最初の TextBox tb1に入力して、ボタンが押すと、3つの TextBox 表示が同じになります。
  3. tb1への入力が自動的にdp1に反映し、dp3への代入がtb3の表示に自動的に反映します。
  1. public partial class Window1 : Window
  2. {
  3.     public Window1()
  4.     {
  5.         InitializeComponent();
  6.     }
  7.     //依存関係プロパティ1
  8.     public string dp1
  9.     {
  10.         get { return (string)GetValue(dp1Property); }
  11.         set { SetValue(dp1Property, value); }
  12.     }
  13.     public static readonly DependencyProperty dp1Property
  14.         = DependencyProperty.Register("dp1", typeof(string), typeof(Window1));
  15.     //依存関係プロパティ3
  16.     public string dp3
  17.     {
  18.         get { return (string)GetValue(dp3Property); }
  19.         set { SetValue(dp3Property, value); }
  20.     }
  21.     public static readonly DependencyProperty dp3Property
  22.         = DependencyProperty.Register("dp3", typeof(string), typeof(Window1));
  23.     //ボタン押下
  24.     private void Button_Click(object sender, RoutedEventArgs e)
  25.     {
  26.         tb2.Text = dp1; //TextBoxのTextに代入
  27.         dp3 = dp1;      //依存関係プロパティに代入
  28.     }
  29. }

3.タイマで参照すると

  タイマで、ボタン押下のときと同じ処理をして見ました。
  この場合は、tb1の入力は、nullのままで、反映されません。
  これは少し意外です。このタイマは、Dispacher 経由のもので、同じスレッドで動作します。これでも同期を取る仕組みをパスしてしまうようです。

  1. System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
  2. private void Grid_Loaded(object sender, RoutedEventArgs e)
  3. {
  4.     timer.Tick += new EventHandler(timer_Tick);
  5.     timer.Interval = new TimeSpan(0, 0, 5);
  6.     timer.Start();
  7. }
  8. void timer_Tick(object sender, EventArgs e)
  9. {
  10.     tb2.Text = dp1; //TextBoxのTextに代入
  11.     dp3 = dp1;      //依存関係プロパティに代入
  12. }


横浜 不動産 足立区 新築一戸建 アルパイン 東戸塚 マンション 横浜 マンション