首页 文章

通过绑定值选择控件样式

提问于
浏览
2

我有一个编辑器视图,可用于多个编辑对象 . 多个对象的视图模型为每个需要处理的字段提供类型为bool的Field1Multiple属性 . 在这种情况下,它现在只是ComboBox控件 . 每当为该字段指示多个不同的值时,应该对App.xaml中定义的该控件应用某种样式 . 该样式更改了控件的背景,以显示此处没有可显示的单个值 .

我试过这个XAML代码:

<ComboBox
  ItemsSource="{Binding Project.Field1Values}" DisplayMemberPath="DisplayName"
  SelectedItem="{Binding Field1}">
  <ComboBox.Style>
    <Style>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Field1Multiple}" Value="true">
          <Setter
            Property="ComboBox.Style"
            Value="{StaticResource MultiValueCombo}"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ComboBox.Style>
</ComboBox>

但它不起作用,因为我无法在Style中设置Style属性 . 如果我直接在控件上使用触发器,可能只有EventTriggers,没有DataTriggers,编译器说 .

如何根据绑定值设置控件的样式?或者,如果绑定值为true,如何为控件设置某种样式?

1 回答

  • 5

    (编辑到完整解决方案)

    你可以使用转换器:

    public class AnyIsMultipleToStyle : IValueConverter
        {
            public Style NormalStyle { get; set; }
    
            public Style MultiStyle { get; set; }
    
    
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value != null)
                {
                    IList<SampleClass> list= value as IList<SampleClass>;
                    if (list!=null)
                    {
                        if (list.Any(i => i.Multi))
                            return MultiStyle;
    
                    }
    
                }
                return NormalStyle;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    并在你的xaml :(你指示正常的风格和多元转换器)

    <Window.Resources>
    
            <Style x:Key="MultiValueCombo"  TargetType="{x:Type ComboBox}">
    
                <Setter Property="Background" Value="Olive" />
            </Style>
    
            <Style x:Key="NormalCombo"  TargetType="{x:Type ComboBox}">
                <Setter Property="Background" Value="Red" />
            </Style>
            <my:AnyIsMultipleToStyle x:Key="AnyIsMultipleToStyle1" MultiStyle="{StaticResource MultiValueCombo}" NormalStyle="{StaticResource NormalCombo }"  />
    
    
    
    
    
        </Window.Resources>
        <Grid>
    
            <ComboBox    ItemsSource="{Binding Items, ElementName=root}"  >
                <ComboBox.Style>
                    <Binding Converter="{StaticResource AnyIsMultipleToStyle1}" Path="Items" ElementName="root" >
    
                        </Binding>
                </ComboBox.Style>
    
            </ComboBox>
        </Grid>
    

相关问题