【问题标题】:WPF ComboBox databinding xaml vs. codeWPF ComboBox 数据绑定 xaml 与代码
【发布时间】:2011-05-20 07:10:30
【问题描述】:

我绝不是 WPF 方面的专家,所以这可能很简单。我正在尝试将列表绑定到组合框。它在代码中有效,在 xaml 中无效。如果我从构造函数中删除 ItemsSource,它就不起作用,这就是我所知道的。我以为我在 xaml 中有等价物,但显然不是。

xaml:

    <ComboBox Height="23"
              HorizontalAlignment="Left"
              Margin="146,76,0,0"
              Name="comboBox1"
              VerticalAlignment="Top"
              Width="120"
              ItemsSource="{Binding AvailableActions}"
              DisplayMemberPath="Name"
              SelectedValuePath="Name"
              SelectedValue="Replace" />

构造函数:

    public MainWindow()
    {
        _availableActions = new List<IMapperAction>
                       {
                           new ReplaceAction(),
                           new CollapseAction(),
                           new NewBasedOnAction()
                       };

        InitializeComponent();
        Loaded += OnWindowLoaded;

        comboBox1.ItemsSource = AvailableActions;
    }

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    嗯,你需要设置主窗口的DataContext

    public MainWindow()
    {
        _availableActions = new List<IMapperAction>
                       {
                           new ReplaceAction(),
                           new CollapseAction(),
                           new NewBasedOnAction()
                       };
    
        InitializeComponent();
        DataContext = this;
        Loaded += OnWindowLoaded;
    }
    

    【讨论】:

    • 哦,我明白了。谢谢!为什么它在代码中起作用?因为它是将上下文推送到 xaml 而不是从 xaml 执行,这意味着需要一个可以与之“对话”的上下文?
    • 在代码中工作,因为您直接设置 itemsource,无需绑定。
    【解决方案2】:

    按照这里的建议,您必须设置 DataContext。

    您还可以阅读此链接以了解为什么以及何时应该使用这两者中的哪一个:

    Why are DataContext and ItemsSource not redundant?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 2011-05-06
      • 2019-06-23
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2011-09-30
      相关资源
      最近更新 更多