WPF-将ComboBox项目绑定到其值的前景 [英] WPF - Bind ComboBox Item Foreground to Its Value

查看:55
本文介绍了WPF-将ComboBox项目绑定到其值的前景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此问题中介绍的方法创建了一个ComboBox,其中列出了System.Windows.Media.Colors预定义的颜色:



任何人都可以帮忙吗?谢谢。



更新:
由于大多数解决方案都有一个将字符串转换为Brush的转换器,实际上我已经拥有它,现在我想把它放在这里,我将TextBox的前景绑定到FontSetting的FontColor属性,以便在更改ComboBox时,该TextBox的颜色也会相应更改。



这是我的转换器类,它可以正常工作现在可以了:

  class StringToBrushConverter:IValueConverter 
{
public object Convert(object value,System。类型targetType,对象参数,System.Globalization.CultureInfo文化)
{
BrushConverter conv = new BrushConverter();
SolidColorBrush brush = conv.ConvertFromString( Lavender)as SolidColorBrush;
if(null!= value)
{
brush = conv.ConvertFromString(value.ToString())为SolidColorBrush;
}
回报刷;
}

公共对象ConvertBack(对象值,System.Type targetType,对象参数,System.Globalization.CultureInfo文化)
{
返回null;
}
}

当我单击组合框以打开下拉列表时,我有一个例外:





结论



胺的解决方案有效,这是我的错误。现在,我简要地解释一下,如果像我一样将ComboBox绑定到System.Windows.Media.Colors,则在渲染项目时,将执行转换器类(分配给绑定)的Convert()方法,实际上,作为第一个参数传递给Convert()的值是Syetem.Windows.Media.Color实例。我误认为是字符串类型。



因此,在我的情况下,我需要两个转换器类,一个将字符串转换为Brush,另一个将Color转换刷。因此,我将保留自己的StringToBrush转换器,并添加Amine的ColorToBrush转换器。



但是,我对Amine的实现进行了一些简化:

 公共对象Convert(对象值,类型targetType,对象参数,CultureInfo文化)
{
BrushConverter conv = new BrushConverter();
SolidColorBrush笔刷= SolidColorBrush)conv.ConvertFromString(FontSetting.DEFAULT_FONT_COLOR);
if(null!= value)
{
PropertyInfo pi = value为PropertyInfo;
if(null!= pi)
{
brush = conv.ConvertFromString(pi.Name)as SolidColorBrush;
}
}
回报刷;
}

此外,Joe的投入也很有价值,将它们放在一起,我可以保留项目的颜色一致,非常完美。

解决方案

您可以将ComboBoxItem的样式设置为波纹管:

 < ComboBox Grid.Column = 1 Grid.Row = 1 Height = 22 Width = 240 x:Name = CB 
VerticalAlignment = Center Horizo​​ntalAlignment = Left
ItemsSource = {Binding Source = {StaticResource colorPropertiesOdp}}
DisplayMemberPath =名称
SelectedValuePath =名称>
< ComboBox.ItemContainerStyle>
< Style TargetType = ComboBoxItem>
< Setter Property = Foreground Value = {Binding Converter = {StaticResource converter}} />
< / Style>
< /ComboBox.ItemContainerStyle>
< / ComboBox>

通过使用此转换器:

 公共类MyConverter:IValueConverter 
{
公共对象Convert(对象值,类型targetType,
对象参数,CultureInfo文化)
{
对象obj =((System.Reflection.PropertyInfo)value).GetValue(this,null);
return(SolidColorBrush)new BrushConverter()。ConvertFromString(obj.ToString());
}

公共对象ConvertBack(对象值,类型targetType,
对象参数,CultureInfo文化)
{
返回值;
}
}


I created a ComboBox listing the colors that System.Windows.Media.Colors predefines, using the approach told in this question: How can I list colors in WPF with XAML?

My XAML code now is:

<Window ...>
    <Window.Resources>
        <ObjectDataProvider 
            ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="ColorList" />
        <local:StringToBrushConverter x:Key="FontColorConversions" />
    </Window.Resources>

    <Grid Background="Black">

        ...

        <ComboBox  Grid.Column="1" Grid.Row="1" Height="22" Width="240" 
                   VerticalAlignment="Center" HorizontalAlignment="Left"
                   ItemsSource="{Binding Source={StaticResource ColorList}}"
                   SelectedValue="{Binding FontColor, Mode=TwoWay}"
                   DisplayMemberPath="Name"
                   SelectedValuePath="Name">
            <ComboBox.ItemContainerStyle>
                <Style TargetType="ComboBoxItem">
                    <Setter Property="Foreground" Value="{Binding Converter={StaticResource FontColorConversions}}"/>
                </Style>
            </ComboBox.ItemContainerStyle>
        </ComboBox>
        ...
    </Grid>
</Window>

And besides, please note that I bind SelectedValue to a VM class's FontColor property, which is of string type.

class FontSetting : INotifyPropertyChanged
{
    private string _fontColor = "Lavender";   // initial color
    public event PropertyChangedEventHandler PropertyChanged;

    public string FontColor
    {
        get
        {
            return _fontColor;
        }
        set
        {
            _fontColor = value;
            OnPropertyChanged("FontColor");
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

And I set the DataContext of the Window containing this ComboBox to an instance of FontSetting.

So each item in the ComboBox actually display a string representing a certain color now, what I want to do is set an item's Foreground color to that color its content indicates, like this:

Can anyone help? Thanks.

UPDATED: Since most of the solutions have a converter which converts string to Brush and actually I already have it, now I want to put mine here, as I binded a TextBox's Foreground to FontSetting's FontColor property, so that when you change the ComboBox, the color of that TextBox changes accordingly.

Here is my converter class, and it works fine by now:

   class StringToBrushConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BrushConverter conv = new BrushConverter();
            SolidColorBrush brush = conv.ConvertFromString("Lavender") as SolidColorBrush;
            if (null != value)
            {
                brush = conv.ConvertFromString(value.ToString()) as SolidColorBrush;
            }
            return brush;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }

When I click the ComboBox to open the dropdown list, I got an exception:

CONCLUSION

Amine's solution works, it's my mistake. I explain briefly now, if you bind a ComboBox to System.Windows.Media.Colors like what I am doing, when the item is rendered, the Convert() method of the converter class (which you assign to the binding) is executed, and actually the value passed to Convert() as its first parameter is a Syetem.Windows.Media.Color instance. I made mistake coz I thought it was of string type.

Therefore, in my case I need two converter classes, one converting string to Brush, and the other one converting Color to Brush. So I will keep my own StringToBrush converter and add Amine's ColorToBrush converter.

However, I simplified Amine's implementation a bit:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    BrushConverter conv = new BrushConverter();
    SolidColorBrush brush = SolidColorBrush)conv.ConvertFromString(FontSetting.DEFAULT_FONT_COLOR);
    if (null != value)
    {
        PropertyInfo pi = value as PropertyInfo;
        if (null != pi)
        {
            brush = conv.ConvertFromString(pi.Name) as SolidColorBrush;
        }
    }
    return brush;
}

Moreover, Joe's input is also valuable, put all them together, I can keep the items' color consistent, which is perfect.

解决方案

You can set Style of ComboBoxItem as bellow :

    <ComboBox  Grid.Column="1" Grid.Row="1" Height="22" Width="240" x:Name="CB"
               VerticalAlignment="Center" HorizontalAlignment="Left"
               ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
               DisplayMemberPath="Name"
               SelectedValuePath="Name">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Foreground" Value="{Binding Converter={StaticResource converter}}"/>
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>

By using this converter:

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        object obj = ((System.Reflection.PropertyInfo)value).GetValue(this,null);           
        return (SolidColorBrush)new BrushConverter().ConvertFromString(obj.ToString());
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return value;
    }
}

这篇关于WPF-将ComboBox项目绑定到其值的前景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆