DataContext控件:用于定义一个数据源,数据源可以绑定到某个元素上
绑定本地对象:
- <ComboBox HorizontalAlignment="Left" Margin="11,33,0,0" VerticalAlignment="Top" Width="90"
- ComboBox 的IsEnabled属性 绑定Check的 IsChecked属性
- Name="playersComboBox" SelectedIndex="0" IsEnabled="{Binding ElementName=playChecked Path=IsChecked}"/>
静态绑定到外部对象:
- <Canvas.Resources>
- <local:NumberOfPlayers x:Key="numberOfPlayersData" />
- </Canvas.Resources>
- <ComboBox HorizontalAlignment="Left" Margin="196,58,0,0" VerticalAlignment="Top" Width="86" Name="numberOfPlayersComboBox" ItemsSource="{Binding Source={StaticResource numberOfPlayersData}}" SelectedValue="{Binding Path=NumberOfPlayers}" />
窗口命令绑定:
绑定数据源
- <Window.DataContext >
- <local:GameViewModel />
- </Window.DataContext>
绑定命令
- <Window.CommandBindings>
- //关闭命令
- <CommandBinding Command="ApplicationCommands.Close"
- CanExecute="CommandCanExecute" Executed="CommandExecuted" />
- //保存命令
- <CommandBinding Command="ApplicationCommands.Save"
- CanExecute="CommandCanExecute" Executed="CommandExecuted" />
- </Window.CommandBindings>
代码隐藏文件:
- private void CommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
- {
- if (e.Command == ApplicationCommands.Close)
- e.CanExecute = true;
- if (e.Command == ApplicationCommands.Save)
- e.CanExecute = true;
- e.Handled=true;
- }
- private void CommandExecuted(object sender, ExecutedRoutedEventArgs e)
- {
- if (e.Command == ApplicationCommands.Close)
- this.Close();
- e.Handled = true;
- }