【问题标题】:How to change color of a rectangle with a binding如何使用绑定更改矩形的颜色
【发布时间】:2019-10-23 18:40:20
【问题描述】:

我在 WPF 中有一个带有文本和彩色矩形的 ListView。另外还有一个文本框和一个绑定到 ListView 的矩形。列表框的选中项显示在文本框和矩形中:

<ListView x:Name="StatusOEMList" HorizontalAlignment="Left" Height="195" Margin="50,50,0,0" VerticalAlignment="Top" Width="255" ItemsSource="{Binding OEM}" IsSynchronizedWithCurrentItem="True">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Status" DisplayMemberBinding="{Binding value}" />
            <GridViewColumn Header="Farbe">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Rectangle Width="10" Height="10" Fill="{Binding color, Converter={StaticResource ColorToBrushConverter}}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>
<TextBox HorizontalAlignment="Left" Height="23" Margin="50,272,0,0" TextWrapping="Wrap" Text="{Binding ElementName=StatusOEMList, Path=SelectedItem.value}"  VerticalAlignment="Top" Width="120"/>
<Rectangle Fill="{Binding ElementName=StatusOEMList, Path=SelectedItem.color, Converter={StaticResource ColorToBrushConverter}}" HorizontalAlignment="Left" Height="23" Margin="192,272,0,0" Stroke="Black" VerticalAlignment="Top" Width="23" MouseLeftButtonDown="rectangle_MouseLeftButtonDown" Cursor="Pen"/>

当我更改文本时,更改会传输回 ListView。好的。 但是如何更改矩形的颜色并将更改传输回 ListView? 我实现了一个 ColorPicker 来改变矩形的颜色:

void rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ColorDialog colorDialog = new ColorDialog();
    colorDialog.SelectedColor = ((SolidColorBrush)((Rectangle)sender).Fill).Color;
    colorDialog.Owner = this;
    if ((bool)colorDialog.ShowDialog())
    {
        ((Rectangle)sender).Fill = new SolidColorBrush(colorDialog.SelectedColor);
    }
}

我想我正在覆盖 Rectangle.Fill 中的 Binding。我怎样才能改变颜色并保持绑定?

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    你确实用本地值覆盖了 Rectangle.Fill 绑定。尝试更改绑定属性:

    void rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        ColorDialog colorDialog = new ColorDialog();
        colorDialog.SelectedColor = ((SolidColorBrush)((Rectangle)sender).Fill).Color;
        colorDialog.Owner = this;
        if ((bool)colorDialog.ShowDialog())
        {
            var vm = StatusOEMList.SelectedItem as MyViewModel;
            vm.color = colorDialog.SelectedColor;
        }
    }
    

    【讨论】:

    • 但是您忽略了 mvvm 设计原则并从视图中操作 viewmodel,应该考虑使 buttondown 动作从 viewmodel 启动而不是代码后面,因此只更新绑定源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多