c# - 在 XAML 中绑定(bind)其 SelectedItem 和 ItemsSource 时设置 ComboBox 的 SelectionChanged 事件

标签 c# wpf xaml mvvm data-binding

我正在尝试设置一个组合框,其选项从字符串列表绑定(bind),其默认选择值从设置绑定(bind),并且其选择的事件处理程序已更改。

我想像这样使用 XAML 配置它:

    <ComboBox Name="RoutesComboBox"
              ItemsSource="{Binding Routes}"
              SelectedItem="{Binding DefaultRoute}" 
              SelectionChanged="RouteFilter_SelectionChanged" />

但是当我在启动时这样做时会引发错误:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll



如果我只在 XAML 中做一些,那么要么设置 SelectionChanged事件或 ItemsSource像下面这样在 C# 中以编程方式工作正常。但是我有很多这样的组合框,所以我宁愿直接在 XAML 中进行。
<ComboBox Name="RoutesComboBox"
          ItemsSource="{Binding Routes}"
          SelectedItem="{Binding DefaultRoute}" />

使用这个 C#:
public IEnumerable<string> Routes
{
    get { return LubricationDatabase.GetRoutes(); }
}

public string DefaultRoute
{
    get { return MySettings.Default.DefaultRoute; }
    set { } /* side question: without this, it throws a parse exception. Any idea why? */
}

public MainWindow()
{
     this.DataContext = this;
     InitializeComponent();

     RoutesComboBox.SelectionChanged += RouteFilter_SelectionChanged;
 }

我也试过找到的解决方案 here :
private string _defaultRoute;
public string DefaultRoute
{
    get { return MySettings.Default.DefaultRoute; }
    set
    {
        if (_defaultRoute != value)
        {
            _defaultRoute = value;

            // this fires before `SelectedValue` has been 
            // updated, and the handler function uses that,
            // so I manually set it here.
            RoutesComboBox.SelectedValue = value;
            SelectionChangedHandler(); 
        }
    }
}

这没关系,但是当我可以以编程方式分配 SelectionChanged 时,它相当庞大,并且可能比值得做的工作更多。事件。

如果可能的话,我想再次使用 XAML 来完成这一切,因为我有很多这样的组合框,并且在 C# 中像这样初始化它们看起来很糟糕。

有任何想法吗?

最佳答案

你为什么要绑定(bind)SelectedItem当用户更改他们的选择时您不打算更新项目?不确定您的事件处理程序在做什么,但我有一个您想要的工作解决方案。

简而言之,您需要跟踪 DefaultRoute使用支持字段。此外,当您的 View 模型中的选定项目发生变化时,您需要通知 UI;顺便说一句,这似乎是你没有做的事情,MVVM。如果您计划以某种方式更新 View ,您应该只 Hook 到选择更改事件。所有其他更改都应在您的 View 模型中处理 DefaultRoute二传手

XAML

<ComboBox Name="RoutesComboBox"
      ItemsSource="{Binding Routes}"
      SelectedItem="{Binding DefaultRoute}" 
      SelectionChanged="RouteFilter_SelectionChanged" />

代码
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public IEnumerable<string> Routes
    {
        get
        {
            return new string[] { "a", "b", "c", "d" };
        }
    }

    public string DefaultRoute
    {
        get
        {
            return _defaultRoute;
        }
        set
        {
            _defaultRoute = value;
            // Handle saving/storing setting here, when selection has changed
            //MySettings.Default.DefaultRoute = value;
            NotifyPropertyChanged();
        } 
    }

    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();

        DefaultRoute = MySettings.Default.DefaultRoute;
    }

    private string _defaultRoute;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void RouteFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }
}

public static class MySettings
{
    public static class Default
    {
        public static string DefaultRoute = "a";
    }
}

关于c# - 在 XAML 中绑定(bind)其 SelectedItem 和 ItemsSource 时设置 ComboBox 的 SelectionChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32871618/

相关文章:

c# - Microsoft.Office.Interop.Word.Application.Documents.Open ("C:\\doc.doc") 未打开

c# - MySql 中的 SqlBulkCopy 等价物?

c# - 将两个具有重复值的 List<int> 相交

c# - 当 MainWindow 完全用 C# 构建时,我在哪里可以添加方法调用

c# - WPF 中的数据绑定(bind)?

c# - 带有固定标题的 ComboBox

wpf - asp.net中的ViewModel与WPF中的ViewModel可比吗

c# - 未找到 Clickonce 部署外部 dll 引用

wpf - 在 ComboBoxItem 中设置文本颜色

c# - XAML(Metro 应用程序)- 如何将 FadeInThemeAnimation 延迟一秒