Domanda

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>

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
    }
    ...
};

And ComboboxPair looks like this:

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

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?

È stato utile?

Soluzione

You could listen to the CopyingCellClipboardContent event:

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

The handler would be something like this:

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

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;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top