当组框控件的IsEnabled状态被绑定到某个视图模型时,该控件的IsEnabled状态没有传播到子按钮
本文关键字:IsEnabled 状态 控件 按钮 传播 绑定 视图 模型 | 更新日期: 2023-09-27 18:14:15
Groupbox包含一个Grid,其中包含两个按钮。
希望代码能更好地表达它:
<Window x:Class="PanelTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="344" Width="361"
x:Name="This">
<Grid>
<GroupBox x:Name="_groupBox" IsEnabled="False" Header="GroupBox" HorizontalAlignment="Left" Margin="30,87,0,0" VerticalAlignment="Top" Height="206" Width="300">
<Grid>
<Button Content="Bound Button" IsEnabled="{Binding IsEnabled, Mode=TwoWay}" HorizontalAlignment="Left" Height="51" VerticalAlignment="Top" Width="128" Margin="140,75,0,0"/>
<Button Content="Unbound Button" HorizontalAlignment="Left" Margin="10,75,0,0" VerticalAlignment="Top" Width="125" Height="51"/>
</Grid>
</GroupBox>
<Button Content="Toggle Group Enabled" HorizontalAlignment="Left" Margin="93,29,0,0" VerticalAlignment="Top" Width="161" Click="EnableClick" Height="35"/>
</Grid>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new ButtonViewModel();
}
private void EnableClick(object sender, RoutedEventArgs e)
{
_groupBox.IsEnabled = !_groupBox.IsEnabled;
}
}
public class ButtonViewModel : INotifyPropertyChanged {
static ButtonViewModel() {
eventArgCache = new Dictionary<string, PropertyChangedEventArgs>();
}
bool _enabled;
public bool IsEnabled {
get { return _enabled; }
set {
if (_enabled == value)
return;
_enabled = value;
RaisePropertyChanged("IsEnabled");
}
}
…}
当我切换组框的启用状态时,我期望IsEnabled属性被设置,但它根本没有被调用,并且绑定的按钮也没有采用组框的启用状态。
是否有一种方法可以使(双向)绑定和亲子关系同时工作?
使用this将button的属性绑定到groupbox的属性
<GroupBox x:Name="_groupBox" IsEnabled="False" Header="GroupBox" HorizontalAlignment="Left" Margin="30,87,0,0" VerticalAlignment="Top" Height="206" Width="300">
<Grid>
<Button Content="Bound Button" IsEnabled="{Binding IsEnabled, ElementName=_groupBox}" HorizontalAlignment="Left" Height="51" VerticalAlignment="Top" Width="128" Margin="140,75,0,0"/>
<Button Content="Unbound Button" HorizontalAlignment="Left" Margin="10,75,0,0" VerticalAlignment="Top" Width="125" Height="51"/>
</Grid>
</GroupBox>
注:IsEnabled="{Binding IsEnabled, ElementName=_groupBox}"
其次,没有已知的方法来绑定按钮的属性来匹配_groupBox &视图模型,当它们都不同时。例如_groupBox.IsEnabled is false
和viewmodel.IsEnabled is true
,但是计算属性可以帮助您执行这样的逻辑