【问题标题】:DataContext: Updating comboBox's ItemSourceDataContext:更新组合框 ItemSsource
【发布时间】:2016-12-15 20:08:21
【问题描述】:

我希望能够更新我的网格中的组合框。我假设我需要某种事件系统。

我是这样绑定的:

<ComboBox Name="ScreenLocations" Grid.Row="1" Margin="0,0,0,175" ItemsSource="{Binding Path=CurrentPlayer.CurrentLocation.CurrentDirections}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValue="{Binding Path= Location}"/>

我的xaml.cs如下:

public partial class MainWindow : Window
{
     GameSession _gameSession;

    public MainWindow()
    {
        InitializeComponent();

        _gameSession = new GameSession();
        DataContext = _gameSession;

    }
}

我希望能够更改 CurrentDirections 属性并在 UI 中更新它。

我绑定的类和属性是:

public  class Location
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }       
    public Quest[] AvailableQuests { get; set; }
    public Monster[] LocationMonsters { get; set; }
    public Location[] CurrentDirections { get; set; }


    public Location(string name, string description, Quest[] availableQuests, int id)
    {
        Name = name;
        Description = description;         
        AvailableQuests = availableQuests;
        ID = id;
        CurrentDirections = new Location[] { };
        LocationMonsters = new Monster[] { };
        AvailableQuests = new Quest[] { };
    }
}

【问题讨论】:

    标签: c# events data-binding combobox datacontext


    【解决方案1】:

    您只需要在类 Location 上实现接口 System.ComponentModel.INotifyPropertyChanged。这将要求您定义感兴趣的各方(例如绑定的 ComboBox)可以订阅的 PropertyChanged 事件以检测更改,然后您可以重新实现 CurrentDirections,如下所示,以便通过此事件通知相关方更改:

    private Location[] currentDirections;
    public  Location[] CurrentDirections 
    { 
        get {return currentDirections;} 
        set {currentDirections = value;  if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("CurrentDirections"));}
    }
    

    为了完整起见,您应该考虑在 Player 和 Location 的其他属性上实现此接口。

    【讨论】:

    • 查看了 INotiftyPropertyChanged 并实现了我想要的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多