我的WPF应用程序中有一个ComboBox,在其中显示项目列表。在大多数情况下,第一个项目是itemssource列表中的正确选择,只有在个人要求下有时才可以更改该项目。现在,我的组合框将加载列表,但从不显示所选项目的第一个项目。有人可以帮我吗。这是我的代码。

XAML:

<ComboBox Name="cbxShipTo" TabIndex="0" IsTextSearchEnabled="True" ToolTip="Ship To is a Required Field" MinWidth="200" SelectedIndex="0" IsSynchronizedWithCurrentItem="True"
IsEditable="False" DisplayMemberPath="ShipToCountyState" SelectedValuePath="ShipToValue">
<ComboBox.SelectedValue>
    <Binding Path="ShipToQAD" Mode="TwoWay">
        <Binding.ValidationRules>
            <common:RequiredValidationRule ErrorMessage="Ship To is a Required Field" />
            <ExceptionValidationRule></ExceptionValidationRule>
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedValue>




背后的代码:

cbxShipTo.ItemsSource = dbLookupService.GetShipToByCustomer(_inspectionListItems[0].CompanyID);
cbxShipTo.SelectedItem = cbxShipTo.Items.GetItemAt(0);


我在itemsSource中有值,Selected itme也有一个值,但从未显示在屏幕上。

任何帮助表示赞赏。

最佳答案

我通常这样做的方法是在ViewModel中保留对当前选定项的引用。 (考虑到您不应该查询UI对象本身来弄清楚用户的选择,您可能仍然应该这样做。)将YourSelectedItem初始化为想要显示为选定状态的项目。

public List<YourType> YourItems { get; set; }
public YourType SelectedItem = YourItems[index];


然后将SelectedItem绑定到YourItems属性。

<ComboBox ... SelectedItem={Binding YourSelectedItem, Mode=TwoWay} ... />


每当用户在ComboBox中更改选择时,YourSelectedItem属性都会自动更新。

除了SelectedItem之外,您不需要使用其他任何东西。

关于c# - WPF组合框从itemssource的默认选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26595908/

10-09 16:23
查看更多