【问题标题】:How do I update a collection item property that has no bound control in the xaml?如何更新在 xaml 中没有绑定控件的集合项属性?
【发布时间】:2019-09-21 19:48:57
【问题描述】:

我有一个项目集合,比如说:

 class Myclass : INotifyPropertyChanged
 {
     public bool Selected { get; set; }
     public string ChosenValue { get; set; }
 }

然后我有一个此类的可观察集合:

 public ObservableCollection<Myclass> _myObColl

最后我有一个绑定到_myObColl 的列表框和一个绑定到另一个集合的单独组合框。

我想更新组合框以更新 _myObColl 列表中所有项目的 ChosenValue 属性。但我不知道怎么做。

组合框选定项绑定到视图模型中称为 currselection 的属性。我想要做的是将 Myclass 的 ChosenValue 属性绑定到 currselection 值。但是我该怎么做呢?也许我不应该考虑绑定,但我想不出另一种方法来更新 items ChosenValue 属性。我尝试了组合的SelectionChanged 事件来循环通过_myObColl。除非在更改组合框后将项目标记为选中,否则此方法有效。

<ComboBox ItemsSource="{Binding Path=DataContext.lstComboList , ElementName=PS4}" SelectedItem="{Binding Path=currselection, Mode=TwoWay}" Margin="10,10,10,10" Width="100"/>
     <ListBox ItemsSource="{Binding _myObColl}" Margin="10,10,0,0" >
            <ListBox.ItemTemplate x:Uid="asdasd"  >
                <DataTemplate>
                     <Grid>
                        <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>         
                        <CheckBox Grid.Column ="3" Width="50" VerticalAlignment="Center" Margin="10"  IsChecked="{Binding Path=PropA, Mode=TwoWay}"/>
                    </Grid>
                 </DataTemplate>
             </ListBox.ItemTemplate>
    </ListBox>

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    如果您希望组合框更改列表框中所选项目的值,您可以像这样绑定 SelectedItem。

    <ComboBox ItemsSource="{Binding ComboList}" SelectedItem="{Binding ElementName=listBox, Path=SelectedItem.ChosenValue}" />
    

    否则,如果您真的想在组合框更改时更改列表中所有项目的属性,则需要在属性设置器中的代码中进行。

    <ComboBox ItemsSource="{Binding ComboList}" SelectedItem="{Binding SelectedValue}"/>
    

    在视图模型中

    private string _SelectedValue;
    public string SelectedValue
    {
        get => _SelectedValue;
        set
        {
            _SelectedValue = value;
            foreach (var item in MyObColl.ToList()) item.ChosenValue = _SelectedValue;
        }
    }
    

    【讨论】:

    • 谢谢@neilB 我以为我可以通过出价来实现这一点,但我可以让 SelectedValue 集属性为我工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多