首页 > 解决方案 > 如何将 ColorPicker 添加到 Datagrid Cell - MVVM Light

问题描述

如何将 ColorPicker 添加到数据网格中的单元格?

我正在做的是使用 Newtonsoft 将 JSON 对象保存在文本文件中,然后在数据网格中显示它们,对象的保存和加载工作正常,但不完全是我想要的。我的问题是我希望能够保存十六进制数字,然后能够加载它们并将它们显示为 ColorPicker 中的颜色。我现在拥有它的方式是使用字符串来保存十六进制数字,并在加载它们时将负载作为简单文本加载,这不是我想要的。

所以这里的主要问题是,如何将 ColorPicker 添加到数据网格中的单元格中并显示颜色?

这是我所拥有的...

在此处输入图像描述

XAML

    <Window x:Class="Tool.Views.WiresView"
            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:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
            xmlns:ignore="http://www.galasoft.ch/ignore"
            mc:Ignorable="d ignore"
            Title="Wires" Height="715" Width="790"
            DataContext="{Binding WiresDialogBox, Source={StaticResource Locator}}">

        <Grid>
            <DataGrid x:Name="dataGrid"
                      ItemsSource="{Binding WiresObservableCollection}"
                      AutoGenerateColumns="False">

                <DataGrid.Columns >
                    <DataGridTextColumn Header="Length" Binding="{Binding WireLength}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Color" Binding="{Binding WireColor}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Description" Binding="{Binding WireDescription}"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>

模型

public class Wire
{
    public string WireLength { get; set; }
    public string WireColor { get; set; }
    public string WireDescription { get; set; }
}

仅供参考 - 我正在使用MVVM Light,Newtonsoft来解析 JSON 对象和toolkitColorPicker。

标签: c#wpfmvvmwpf-controlsmvvm-light

解决方案


DataGridTemplateColumn按照建议使用ASh

这是我的做法。

            <DataGrid.Columns >
                <DataGridTextColumn Header="Length" Binding="{Binding WireLength}"></DataGridTextColumn>

               <DataGridTemplateColumn Header="Color" SortMemberPath="WireColor">
                  <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                           <Label  Background="{Binding Path=WireColor, Mode=TwoWay}"/>
                      </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
               </DataGridTemplateColumn>

                <DataGridTextColumn Header="Description" Binding="{Binding WireDescription}"></DataGridTextColumn>
            </DataGrid.Columns>

推荐阅读