本文介绍了将 ClipboardContentBinding 绑定到 DisplayMemberPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 DataGridComboBoxColumn:

I have a DataGridComboBoxColumn like this:

<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 列表,如下所示:

The ElementStyle binds to a list of ComboboxPairs like this:

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

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

ComboboxPair 看起来像这样:

And ComboboxPair looks like this:

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

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

This allows me to display a helpful name in the combobox, but to bind a float to the viewmodel when a user selects a value. However, when I select a row and copy it, I get the floating point value. I would like to get the helpful name. Is there a way to bind the DataGridComboBoxColumn's ClipboardContentBinding to its DisplayMemberPath, or is this the wrong approach? How else could I do this?

推荐答案

您可以聆听 CopyingCellClipboardContent 事件:

<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 方法:


Alternatively, if you want to subclass the DataGridComboBoxColumn class, you could override its OnCopyingCellClipboardContent method:

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

这篇关于将 ClipboardContentBinding 绑定到 DisplayMemberPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:33