我想將ComboBox的IsEnabled屬性綁定到複選框的IsChecked屬性,而我希望只有在複選框值爲FALSE時才能使用ComboBox。如何將屬性綁定爲false值
IsEnabled="{Binding ElementName=RegexCbx, Path=IsChecked}"
這樣做的最簡單方法是什麼?
我想將ComboBox的IsEnabled屬性綁定到複選框的IsChecked屬性,而我希望只有在複選框值爲FALSE時才能使用ComboBox。如何將屬性綁定爲false值
IsEnabled="{Binding ElementName=RegexCbx, Path=IsChecked}"
這樣做的最簡單方法是什麼?
使用樣式觸發:
<StackPanel>
<CheckBox x:Name="Foo" Content="Click me"/>
<ComboBox>
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=Foo}" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
</StackPanel>
從的IValueConverter衍生應該做的伎倆類:
public class BoolToOppositeBoolConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
最好是在資源字典,創建轉換器的實例:
<converters:BoolToOppositeBoolConverter x:Key="oppositeBoolConverter" />
然後在你的視圖中,做這樣的事情,其中IsChecked的bool值被轉換爲t o相反的價值。不要忘記包含資源字典作爲視圖的資源。
<TextBox IsEnabled="{Binding IsChecked, Converter={StaticResource oppositeBoolConverter}" />
另一種方式來做到這一點,就是用混合的DataTrigger
:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"
<ComboBox>
<i:Interaction.Triggers>
<ie:DataTrigger Binding="{Binding IsChecked, ElementName=RegexCbx}"
Value="False">
<ie:ChangePropertyAction PropertyName="IsEnabled"
TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox}}"
Value="True"/>
</ie:DataTrigger>
<ie:DataTrigger Binding="{Binding IsChecked, ElementName=RegexCbx}"
Value="True">
<ie:ChangePropertyAction PropertyName="IsEnabled"
TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox}}"
Value="False"/>
</ie:DataTrigger>
</i:Interaction.Triggers>
</ComboBox>
好,最簡單的方法是'DataTrigger'和更好的方式是'ValueConverter' – Gopichandar
只需使用一個轉換器 – blindmeis