C#windows编程:数据绑定

DataContext控件:用于定义一个数据源,数据源可以绑定到某个元素上

绑定本地对象:

  1. <ComboBox  HorizontalAlignment="Left" Margin="11,33,0,0" VerticalAlignment="Top" Width="90"
  2.                                                                                  ComboBox 的IsEnabled属性  绑定Check的 IsChecked属性  
  3. Name="playersComboBox" SelectedIndex="0"  IsEnabled="{Binding ElementName=playChecked Path=IsChecked}"/>

静态绑定到外部对象:

  1. <Canvas.Resources>
  2.         <local:NumberOfPlayers x:Key="numberOfPlayersData" />
  3. </Canvas.Resources>
  4.  
  5.  <ComboBox HorizontalAlignment="Left" Margin="196,58,0,0" VerticalAlignment="Top" Width="86" Name="numberOfPlayersComboBox" ItemsSource="{Binding Source={StaticResource numberOfPlayersData}}" SelectedValue="{Binding Path=NumberOfPlayers}" />

窗口命令绑定:

      绑定数据源

  1. <Window.DataContext >
  2.     <local:GameViewModel />
  3.   </Window.DataContext>

      绑定命令

  1.   <Window.CommandBindings>
  2.     //关闭命令
  3.     <CommandBinding Command="ApplicationCommands.Close"
  4.         CanExecute="CommandCanExecute" Executed="CommandExecuted" />
  5.     //保存命令
  6.     <CommandBinding Command="ApplicationCommands.Save" 
  7.         CanExecute="CommandCanExecute" Executed="CommandExecuted" />
  8.     </Window.CommandBindings>

代码隐藏文件:

  1.  private void CommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
  2.     {
  3.       if (e.Command == ApplicationCommands.Close)
  4.         e.CanExecute = true;
  5.       if (e.Command == ApplicationCommands.Save)
  6.         e.CanExecute = true;
  7.      e.Handled=true;
  8.     }
  9.     private void CommandExecuted(object sender, ExecutedRoutedEventArgs e)
  10.     {
  11.       if (e.Command == ApplicationCommands.Close)
  12.         this.Close();
  13.       e.Handled = true;
  14.     }

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/86395547