我正在使用一些 ComboBoxes,它们的 ComboBoxItems 是一组 StaticResource 字符串。我想通过使用其SELETEDITEM未被选择的INTERSIONINX来更改组合框的可见性以崩溃。
为此,我编写了以下代码,但 Visual Studio 显示此错误消息:“在使用(密封)‘DataTrigger’后,无法对其进行修改。”
<Window x:Class="CB.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:CB"
mc:Ignorable="d"
Title="MainWindow" Height="177" Width="179">
<Window.Resources>
<system:String x:Key="Str1">String1</system:String>
<system:String x:Key="Str2">String2</system:String>
<system:String x:Key="Str3">String3</system:String>
</Window.Resources>
<StackPanel>
<ComboBox x:Name="CB1">
<ComboBoxItem Content="{StaticResource Str1}"/>
<ComboBoxItem Content="{StaticResource Str2}"/>
<ComboBoxItem Content="{StaticResource Str3}"/>
</ComboBox>
<ComboBox x:Name="CB2">
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=CB1, Path=SelectedItem}" Value="{StaticResource Str3}">
<!--Error ^: After a 'DataTrigger' is in use (sealed), it cannot be modified. -->
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
<ComboBoxItem Content="{StaticResource Str1}"/>
<ComboBoxItem Content="{StaticResource Str2}"/>
<ComboBoxItem Content="{StaticResource Str3}"/>
</ComboBox>
</StackPanel>
你能帮我解决这个问题吗,可能使用 WPF 代码?
编辑:请有人回答我的问题!
您可以使用 MultiDataTrigger 代替 DataTrigger 并使用 ComboBoxItemToStringConverter:
public class ComboBoxItemToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var combo = value as ComboBoxItem;
string content = combo?.Content.ToString();
return content;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后你使用:
<Window.Resources>
...
<local:ComboBoxItemToStringConverter x:Key="ObjectToStringConverter" />
</Window.Resources>
<ComboBox.Style>
<Style TargetType="ComboBox">
<Setter Property="Visibility" Value="Visible" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ElementName=CB1, Path=SelectedItem, Converter={StaticResource ComboBoxItemToStringConverter}}" Value="{StaticResource Str3}" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Collapsed" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
我希望这个对你有用。
编辑:如果您不想使用 c# 代码。而不是使用“SelectedItem”使用文本:
<Condition Binding="{Binding ElementName=CB1, Path=Text}" Value="{StaticResource Str3}" />
并删除转换器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句