在ItemTemplate中绑定Ellipse Fill属性

时间:2018-05-16 17:28:34

标签: c# wpf xaml binding

当我添加此代码时,我正在尝试在Combobox中添加彩色椭圆:

<ComboBox Width="300" BorderBrush="#6593CF" Visibility="Visible" BorderThickness="1"  Margin="5" VerticalAlignment="Top" ItemsSource="{Binding Parts}" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0">
                <Label Content="Code" Margin="0" Padding="0"/>
                <Label Content="{Binding reference}" Margin="0" Padding="0"></Label>
                <Label Content="  R " Margin="0" Padding="0"/>
                <Label Content="{Binding R}" Margin="0" Padding="0"></Label>

                <Ellipse Height="20" Width="20" Fill="Red" Margin="0"/>

            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

它起作用并显示红色椭圆;但是当我像这样绑定Ellipse的Fill属性时:

<Ellipse Name="elli" Height="20" Width="20" Fill="{Binding color}" Margin="0"/>

并在ViewModel中添加color属性,它不起作用并在comboBox中显示一个空格。

以下是ViewModel中的属性代码:

public string _color = "Red";
public string color
{
    get
    {
        return _color;
    }

    set
    {
        if (_color == value)
        {
            return;
        }
        _color = value;
        RaisePropertyChanged("color");
    }
}

我也尝试在Datagrid元素中添加Ellipse,但我遇到了同样的问题。

1 个答案:

答案 0 :(得分:0)

在ItemTemplate中,DataContext是组合框项目。这意味着case在组合框项目中查找名为{Binding color}的属性。

color是您的主视图模型的属性,我收集。但是使用该DataTemplate显示color中的每个对象。如果这些对象不具有名为Parts的属性,则您将绑定到任何内容。相同的原则适用于DataGrid单元格模板。

所以你需要找到主视图模型。如果你在一个Window中,那可能就是Window的viewmodel,它将是包含控件的DataContext。所以试试这个组合框:

color

如果你在DataGrid单元格模板中有一个组合框,你需要Fill="{Binding DataContext.color, RelativeSource={RelativeSource AncestorType=ComboBox}}" - 继续向上链,直到你确定你得到一个具有正确DataContext的控件。

我同意Erno的说法,将颜色表示为字符串并不理想,但字符串会起作用。

最好是让你的viewmodel属性成为一个专门的枚举类型,它表示与用户通信的颜色的语义:Info / Warning / Error,OnTime / Early / Delayed - that之类的事情。然后使用值转换器或触发器将其转换为视图中的画笔。

相关问题