【问题标题】:WPF ComboBox databinding ItemsSource item.ToString() to property setter. Why?WPF ComboBox 数据绑定 ItemsSource item.ToString() 到属性设置器。为什么?
【发布时间】:2011-02-01 14:31:48
【问题描述】:

由于某种原因,当我将 ComboBox 绑定到 POCO 列表时,绑定到 SelectedValue 的属性设置了两次:

  1. 值 = POCO.ToString()
  2. 使用 value = POCO.Key 属性,这是预期的行为

我有以下 ComboBox 绑定到我的 ViewModel 中的属性:

<ComboBox ItemsSource="{Binding Path=AllowedClassifications}" 
          DisplayMemberPath="Value" 
          SelectedValue="{Binding Path=TargetGroup.Classification}" 
          SelectedValuePath="Key" />

ViewModel 中的属性定义为:

//ICollection is implemented by ObservableCollection<T>
//DataBaseFieldValue has two public properties: string Key, string Value
public ICollection<DatabaseFieldValue> AllowedClassifications
{
    get { return _allowedClassifications; }
    private set { _allowedClassifications = value; }
}

public Model.TargetGroup TargetGroup
{
    get { return _targetGroup; }
    private set { _targetGroup = value; OnPropertyChanged("TargetGroup"); }
}   

TargetGroup.Classification 定义为:

public string Classification
{
    get { return _classification; }
    set 
    {
        System.Diagnostics.Debug.WriteLine("Classification: " + value);
        _classification = value; 
        OnPropertyChanged("Classification"); 
    }
}

调试输出:

分类: MyNamespace.DatabaseFieldValue

分类:2

这里发生了什么?我这样做完全错了吗?

【问题讨论】:

标签: wpf data-binding mvvm combobox


【解决方案1】:

您的代码中的一切看起来都不错,除了根据您的 XAML 绑定到 SelectedValue 的属性应该设置为 POCO.Key 值而不是 POCO.Value (正如您所期望的那样)。我刚刚创建了一个具有类似设置的测试项目,一切正常。

或者,您可以尝试将组合框的 SelectedItem 属性与 ItemTemplate 结合使用:

<ComboBox ItemsSource="{Binding Path=AllowedClassifications}"    
          SelectedItem="{Binding Path=TargetGroup.Classification}" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

在这种情况下,TargetGroup.Classification 属性必须是 DatabaseFieldValue 类型。

【讨论】:

  • 绑定到 POCO.Key 是正确的,在我的帖子中修复了这个问题。您的示例对我来说是正确的,但不幸的是我无法重新定义我的模型对象。
  • 正是为了这个目的(不必为 UI 重新定义模型对象),所以有 MVVM 模式。您应该围绕它们创建一个视图模型并绑定它,而不是直接绑定到模型对象。在视图模型中,您可以执行 UI 要求的任何操作。
  • 我找不到我的实现不能正常工作的任何原因,所以最终为对象实现了一个 ViewModel - 就像一个魅力。感谢您的建议!
猜你喜欢
  • 2015-04-07
  • 2023-04-01
  • 2011-09-01
  • 2013-09-13
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多