开发者

ComboBox doesn't show current value of assigned field inside a ListView

I have a DataTemplate with a Combobox inside a ListView like this

<GridViewColumn.CellTemplate>
<DataTemplate>
    <ComboBox ItemsSource="{Binding DataContext.Dimensions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
                                DisplayMemberPath="Description"
                                SelectedValuePath="Id"
                                SelectedItem="{Binding DimName}"/>
</DataTemplate>

The combobox is populated correctly, but it doesn't select the content according to underlying field (ie. Dimension.DimName).

Here's how the ListView is declared

<ListView 
  Name="lstCriteria"
  ScrollViewer.VerticalScrollBarVisibility="Auto"
  Margin="5"
  AlternationCount="2" 
  ItemContainerStyle="{StaticResource CriteriaItemStyle}"
  ItemsSource="{Binding Source={StaticResource CriteriaList}}" DockPanel.Dock="Top"
  IsSynchronizedWithCurrentItem="True">    

If I replace combobox with a TextBlock it does show the DimName Field's value, like this

<TextBox Text="{Binding DimName}"/>
开发者_运维技巧

What am I missing ?


Does your DimName come directly from the Dimensions list?

By default, if a ComboBox's Items is set to a custom class, it will compare the SelectedItem to an item in the ItemSource by reference. It will not match the item if they do not refer to the exact same object in memory, even if the object's data is the same.

To get around that you can either set SelectedValue and SelectedValuePath instead of SelectedItem on your ComboBox, or you can overwrite the Equals() method of your DimName class to return true if an object's data is equal

Edit

In regards to your comment below, is DimName a Dimension object? If so then setting SelectedItem should work fine. If it's an long you'll need to set SelectedValue, not SelectedItem. If it's something else, you may need a converter to convert it into a Dimension object


As Rachel suggested, I added a new Property to my class called Dimension of class Dimension like this

    public Dimension Dimension
    {
        get { return _dimension; }
        set { _dimension = value; }
    }

and then set SelectedItem="{Binding Dimension}" as follows,

<ComboBox ItemsSource="{Binding DataContext.Dimensions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
                                              DisplayMemberPath="Description"
                                              SelectedValuePath="Id"
                                              SelectedItem="{Binding Dimension}">
                                            </ComboBox>

The silly mistake I was making was, As my combobox was populating correctly, I was hoping that WPF will somehow match the DimName content with one of the items in the ComboBox automatically, which is not possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜