首页 > 解决方案 > 选择项目时如何阻止组合框将 selectedItem 添加到 itemSource 列表?

问题描述

简而言之,我将组合框的 ItemSource 绑定到对象列表。我将 SelectedItem 绑定到一个属性。问题是:每当我在组合框中选择一个项目并按下一个按钮时,SelectedItem 就会复制自身(它甚至被添加到数据库中)。这不是我想要的。

我曾尝试更改绑定模式和 updateSourceTrigger,但到目前为止这对我来说还没有成功。我还尝试将我的 itemssource 绑定到另一个列表(来自数据库存储库的副本),但问题仍然存在。

XAML(视图):

 <ComboBox Margin="0,15,0,0" DockPanel.Dock="Top" materialDesign:HintAssist.Hint="Table" VerticalAlignment="Top" SelectedItem="{Binding Reservation.Table}" ItemsSource="{Binding Tables}"  DisplayMemberPath="Name" ></ComboBox>

视图模型:

public ObservableCollection<Data.Table> Tables
{
    get { return _tables; }
    set
    {
        SetValue(ref _tables, value);
     }
}
Tables = _tableRepo.GetTables();

按键逻辑:

private void Save()
{
    if (IsNewReservation)
    {

        _reservationRepo.AddReservation(Reservation);
    }
    else
    {
        _reservationRepo.UpdateReservation(Reservation);
    }
}

按钮 XAML:

        <Button Grid.Column="2" Grid.Row="2" FontSize="20" Height="45" Command="{Binding SaveCommand}" Content="Save">
            <Button.IsEnabled>
                <MultiBinding Converter="{StaticResource HasAllTextConverter}">
                    <!--https://www.codeproject.com/Questions/1101746/Need-to-enable-the-button-when-all-textbox-has-val-->
                    <Binding ElementName="LastName" Path="Text"/>
                    <Binding ElementName="AmountPeople" Path="Text"/>
                    <Binding ElementName="Phone" Path="Text"/>
                </MultiBinding>
            </Button.IsEnabled>
        </Button>

我期望 SelectedItem 更新我的属性,而不会对源产生影响。

标签: c#wpfxamlmvvmdata-binding

解决方案


推荐阅读