DataGrid WPF中的xctk ColorPicker

时间:2017-10-29 19:57:14

标签: c# wpf datagrid color-picker

我有一个包含2个单元格的DataGrid,但我想添加另一个包含ColorPicker的单元格:

XAML:

<DataGrid Name="dtg" Grid.Row="2" Grid.Column="0" Grid.RowSpan="3" Width="200"
              HorizontalAlignment="Left" CanUserAddRows="False" CanUserDeleteRows="False" ScrollViewer.CanContentScroll="True"
              ScrollViewer.VerticalScrollBarVisibility="Visible" Margin="50,20,0,15"
              SelectionChanged="rowSelect" AutoGenerateColumns="False" IsReadOnly="false" RowEditEnding="cellc">
        <DataGrid.Resources>
            <Style TargetType="ScrollBar">
                <Setter Property="Background" Value="#FFBFBFBF" />
            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns >
            <DataGridTextColumn Header="n1" IsReadOnly="false" Binding="{Binding n1}" Width="*"/>
            <DataGridTextColumn Header="n2"  IsReadOnly="false"  Binding="{Binding n2}" 
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

填写单元格的类:

 public class data
{
    public int n1 { get; set; }
    public int n2 { get; set; }
}

1 个答案:

答案 0 :(得分:2)

首先,您需要System.Windows.Media.ColorData的属性:

public Color DataColor { get; set; }

现在需要将Extended WPF Toolkit命名空间添加到视图中:

xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"

您可以使用DataGridTemplateColumn使用自定义模板定义数据网格列。只需添加ColorPicker这样的模板并绑定已定义的属性即可。这是一个例子:

<DataGrid>
    <DataGrid.Columns>
        <!-- ... -->
        <DataGridTemplateColumn Header="Color">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate x:Key="ColorCellTemplate">
                    <xctk:ColorPicker SelectedColor="{Binding DataColor, UpdateSourceTrigger=PropertyChanged}"
                         DisplayColorAndName="True" UsingAlphaChannel="False"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <!-- ... -->
    </DataGrid.Columns>
</DataGrid>