简体   繁体   中英

How can I set the initial SelectedItem for a ComboBox bound to an enum, to a Value of an object containing that enum?

I currently have a ComboBox that exists inside a ListView. That ComboBox's ItemSource is bound to a StaticResource Enum, which populates the ComboBox with the enum values I'd like to offer to the user. The ListView itself is bound to a an Observable Collection of Objects, which have a property associated with the enum I'm trying to present. Most of this is working.

The ComboBox is properly displaying and showcases the values from the Enum. It even Starts populated with the first item from the Enum I created. However, I'm trying to get it to show the actual Enum value for the Object that the Listview is presenting, which it's not currently doing. I believe there's an issue with what I'm setting my SelectedValue and SelectedValuePaths to but I'm having trouble figuring out the exact issue.

Here's the XAML I'm using for the ComboBox right now.

<DataTemplate>
  <ComboBox ItemSource={Binding Source={StaticResource dataFromStatusesEnum}}
   SelectedValue="{Binding JMessage3, Mode=TwoWay"}"
   SelectedValuePath="Statuses.Status"
  </ComboBox>
</DataTemplate>

Here's the class I'm filling the ObservableCollection that the ListView is bound to.

public class Entity
{
    public string Name {get; set;}
    public Statuses Status {get; set;}
    Public Entity()
    {
        this.Name = "Test";
        this.Status = Statuses.Disabled;
    }
}

And here's the Enum I'm binding the ComboBox ItemSource to right now.

public enum Statuses
{
    Enabled,
    Disabled,
    Deleted
}

As I understand the XAML I've created, the ListBox is properly Bound to the ItemSource and displaying the information I'd expect.

The ComboBox is properly bound to the Enum and displaying those in the DropDown as options for the ComboBox.

I think the SelectedValuePath SHOULD be the Status property of the Entity Class itself and I think the SelectedValue SHOULD be the enum that I'd like this to be set to, but obviously I'm wrong in this assumption.

Edit: Wanted to add that this is not using the MVVM Pattern currently. Something I'm working toward eventually but not implementing just yet.

Got this working. The SelectedValue should've been set to the Status property of the Entity, and SelectedValuePath didn't have to be set to anything. I'm not entirely sure why but it's working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM