为什么组合框没有选择任何值?

huangapple go评论70阅读模式
英文:

Why combobox not select any value?

问题

以下是XAML代码:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ComboBox x:Name="CB" SelectedValue="{Binding Model, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Value" VerticalAlignment="Center">
        </ComboBox>
    </Grid>
</Window>

以下是代码后台的代码:

public partial class MainWindow : Window
{
    public List<TestModel> Models { get; set; } = new List<TestModel>();
    TestModel _Model = new TestModel() { Key = "Joe", Value = "456" };

    public TestModel Model
    {
        get => _Model; set
        {
            if (_Model != value)
            {
                _Model = value;
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        Models.Add(new TestModel() { Key = "John", Value = "123" });
        Models.Add(new TestModel() { Key = "Joe", Value = "456" });
        Models.Add(new TestModel() { Key = "Kay", Value = "547" });
        Models.Add(new TestModel() { Key = "Rose", Value = "258" });
        CB.ItemsSource = Models;
        this.DataContext = this;
    }

    public class TestModel
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
}

你将SelectedValue绑定到了Model,而Model的初始值是一个TestModel对象,该对象的Key属性是"Joe",但是ComboBoxItemsSource绑定的是ModelsComboBox不知道如何将"Joe"与列表中的哪个项匹配。为了解决这个问题,你可以在Models中查找匹配的项,然后将其分配给Model,或者将SelectedValuePath设置为"Key"以匹配Model的"Key"属性。这将使ComboBox正确选择项。

英文:

Here is the code of XAML:<br/>

&lt;Window x:Class=&quot;WpfApp1.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
        xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
        xmlns:local=&quot;clr-namespace:WpfApp1&quot;
        mc:Ignorable=&quot;d&quot;
        Title=&quot;MainWindow&quot; Height=&quot;450&quot; Width=&quot;800&quot;&gt;
    &lt;Grid&gt;
        &lt;ComboBox x:Name=&quot;CB&quot; SelectedValue=&quot;{Binding Model,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}&quot; DisplayMemberPath=&quot;Value&quot; VerticalAlignment=&quot;Center&quot;&gt;
            
        &lt;/ComboBox&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;

And here is the code of code-behind:

public partial class MainWindow : Window
    {
        public List&lt;TestModel&gt; Models { get; set; } = new List&lt;TestModel&gt;();
        TestModel _Model = new TestModel() { Key = &quot;Joe&quot;, Value = &quot;456&quot; };        

        public TestModel Model
        {
            get =&gt; _Model; set
            {
                if (_Model != value)
                {
                    _Model = value;                    
                }
            }
        }
       
        public MainWindow()
        {
            InitializeComponent();
            Models.Add(new TestModel() { Key = &quot;John&quot;, Value = &quot;123&quot; });
            Models.Add(new TestModel() { Key = &quot;Joe&quot;, Value = &quot;456&quot; });
            Models.Add(new TestModel() { Key = &quot;Kay&quot;, Value = &quot;547&quot; });
            Models.Add(new TestModel() { Key = &quot;Rose&quot;, Value = &quot;258&quot; });
            CB.ItemsSource = Models;
            this.DataContext = this;
        }
        public class TestModel
        {
            public string Key { get; set; }
            public string Value { get; set; }
        }
    }

I bind the SelectedValue to the Model which is already existed in the List. but the selection is still blank.
为什么组合框没有选择任何值?

What's wrong with my code? I need the combobox select the item correctly.

答案1

得分: 0

Model 应该返回 Models 中的一个项目。

在设置 DataContext 之前,请将以下内容添加到构造函数中:

Model = Models[1];

有问题的代码行是
_Model = new TestModel() { Key = "Joe", Value = "456" } - 你创建了一个 TestModel 的实例,该实例不在列表中。即使它具有相同的属性值,它也不是相同的对象。

英文:

Model should return one of the items from Models.

Add this to the constructor before DataContext setter:

Model = Models[1];

The problematic line is
_Model = new TestModel() { Key = &quot;Joe&quot;, Value = &quot;456&quot; } - you create an instance of TestModel that is not present in the list. Even though it has the same property values, it is not the same object.

答案2

得分: 0

ComboBoxes使用它们正在显示的对象的.Equals()方法来查找ItemsSource中的SelectedItem。

由于默认情况下类的Equals()方法通过比较对象引用来工作,您需要将SelectedItem设置为与ItemsSource中的对象的确切相同实例。

您还可以采取另一种方法,即重写对象的Equals()方法,使其通过值比较相等,或者使用记录类,该类会自动使您的对象可通过值比较。

英文:

ComboBoxes use the .Equals() method of the objects they are displaying to find the SelectedItem in the ItemsSource.

Since the Equals() method for clasess by default works by comparing object references, you would need to set the SelectedItem to an exact same instance as an object inside the ItemsSource.

Another approach you could take is overriding the Equals() method on your object and making it Equal by value comparison or use a record class which automatically makes your object comparable by value.

huangapple
  • 本文由 发表于 2023年2月6日 16:45:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定