有没有一种简单的方法可以在单击按钮后将属性IsEnabled设置为false CheckBox控件。请注意,按钮在另一个xaml文件中。是否可以在没有代码隐藏的情况下,只在xaml中完成?
主窗口.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1" x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Content="CheckBox" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<local:UserControl1 HorizontalAlignment="Left" Margin="31,54,0,0" Grid.Row="1" VerticalAlignment="Top"/>
</Grid>
</Window>
用户控制1.xaml
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Width="75"/>
</Grid>
</UserControl>
您必须添加一个bool
属性,并使用ToggleButton
而不是Button
。在这里,我们将CheckBox.IsChecked
属性绑定到bool IsDefault
属性(随意调用),并设置UserControl.DataContext
属性:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Content="CheckBox" IsChecked="{Binding IsDefault}"
HorizontalAlignment="Left" VerticalAlignment="Top"/>
<local:UserControl1 DataContext="{Binding}" HorizontalAlignment="Left"
Margin="31,54,0,0" Grid.Row="1" VerticalAlignment="Top"/>
</Grid>
</Window>
在这里,我们将ToggleButton.IsChecked
属性绑定到bool IsDefault
属性:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<Grid>
<ToggleButton Content="Button" IsChecked="{Binding IsDefault}"
HorizontalAlignment="Left" Width="75" />
</Grid>
</UserControl>
既然它们是数据绑定的,更改其中一个将更新另一个。