gpt4 book ai didi

c# - 设置组合框的选定值

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:31 26 4
gpt4 key购买 nike

我已经对此进行了一些搜索,但似乎没有什么能完全符合我正在寻找的答案。基本上我有一个组合框和组合框中的一个对象。我想将组合框的值设置为对象的值。

ComboBox cbPayee;
// populate with a bunch of "Payee" objects
Payee myObj; // this is my payee object which I get from my database

cbPayee.SelectedValue = myObj // this is what I'd like to do, but it doesn't work

我想这可能与组合框中的 Payee 对象与 myObj 的内存位置不同有关,但我不确定如何克服这个问题。

编辑

这是组合框的填充方式

foreach(Payee payee in PayeeManager.GetPayees())
{
cbPayee.Items.Add(payee);
}

编辑#2

我是 WPF 的新手,所以可能我的绑定(bind)设置不正确?

<Window x:Class="Budget.TransactionWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="New Transaction" Height="450" Width="450" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="PayeeOutput" DataType="Budget.LINQ.Payee">
<StackPanel Margin="0 0 0 0" Orientation="Horizontal">
<TextBlock FontWeight="bold" Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ComboBox Height="25" HorizontalAlignment="Left" Margin="73,50,0,0" Name="cbPayee" VerticalAlignment="Top" Width="300" ItemTemplate="{StaticResource PayeeOutput}" />
</Grid>
</Window>

最佳答案

为了达到你想要的,你可以做到

cbPayee.SelectedItem = myObj;

当你做的时候

cbPayee.SelectedValue = myObj;

发生的事情是 .NET 搜索 Payee具有 ComboBox.SelectedValuePath 指定属性的对象等于myObj (肯定根本就不是对象),找不到这样的对象,结果清除了选择。

更新:

设置SelectedItem应该只是“正常工作”:如果对象在 Items 中收藏,它被选中。这里需要注意的是,在搜索对象时,WPF 默认会使用引用相等性。如果你想为这个场景提供你自己的平等测试,你需要有 Payee实现 IEquatable<Payee> .如果它对您不起作用,请仔细检查您确实指的是同一个实例(或实现 IEquatable )。

此外,如果您这样做:

cbPayee.SelectedValuePath = "Name";
cbPayee.SelectedValue = "Jack Smith";

那么组合框应该选择Payee实例及其 Name等于你指定的。实际上,这很像实现 IEquatable<Payee>通过让实现比较 Name 的值.

到底什么不适合您?

关于c# - 设置组合框的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4286092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com