将ClipboardContentBinding绑定到DisplayMemberPath

时间:2014-01-15 22:05:15

标签: c# wpf xaml datagrid clipboard

我有一个像这样的DataGridComboBoxColumn:

<DataGridComboBoxColumn
    SelectedValueBinding="{Binding
        Path=Offset,
        Mode=TwoWay,
        UpdateSourceTrigger=PropertyChanged}"
    DisplayMemberPath="Key"
    SelectedValuePath="Value">

...

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter
                Property="ItemsSource"
                Value="{Binding
                    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
                    Path=DataContext.Offsets}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

ElementStyle绑定到ComboboxPairs列表,如下所示:

public ObservableCollection<ComboboxPair<float>> Offsets { get; set; }

Offsets = new ObservableCollection<ComboboxPair<float>>
{
    new ComboboxPair<float>
    {
        Key = "Item 1",
        Value = 1.23
    }
    ...
};

ComboboxPair看起来像这样:

public class ComboboxPair<T>
{
    public string Key { get; set; }
    public T Value { get; set; }
}

这允许我在组合框中显示一个有用的名称,但是当用户选择一个值时将float绑定到viewmodel。但是,当我选择一行并复制它时,我得到浮点值。我想得到一个有用的名字。有没有办法将DataGridComboBoxColumn的ClipboardContentBinding绑定到其DisplayMemberPath,或者这是错误的方法?我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以收听CopyingCellClipboardContent event

<DataGridComboBoxColumn x:Name="comboColumn" CopyingCellClipboardContent="OnCopying" ... />

处理程序将是这样的:

void OnCopying(object sender, DataGridCellClipboardEventArgs args)
{ 
    if (args.Column == comboColumn && args.Item as ComboBox<float> != null)
        args.Content = ((ComboBox<float>)args.Item).Key;
}

或者,如果您想要对DataGridComboBoxColumn类进行子类化,则可以覆盖其OnCopyingCellClipboardContent方法:

public class CustomDataGridComboBoxColumn : DataGridComboBoxColumn
{
    public override object OnCopyingCellClipboardContent(object item)
    {
        if (item as ComboboxPair<float> is null)
            return null;
        return ((ComboboxPair<float>)item).Key;
    }
}