当一个属性改变时,如何更新WPF中的两个值

4

我在以下XAML代码中遇到了一些困难:

<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="ListBoxItem">
            <CheckBox  Content="{Binding Element.Region_Code}" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

这段代码将更新包含ListBoxItem的IsSelected属性,从而使我可以从lstRegion.SelectedItems返回此内容。
但是,当复选框的IsChecked值更改时,我还需要更新ItemsSource中的值。 有没有办法同时更新ItemsSource中的值和ListBoxItem?似乎我只能更改其中一个,而不能同时更改两个。 我确定我可以捕获PropertyChanged事件并手动更新值,但这似乎是因为我理解有误而做了额外的步骤。感谢任何帮助。
这是用于填充ListBox上的ItemsSource的类:
 public class SelectionItem<T> : INotifyPropertyChanged
    {
        #region private fields
        /// <summary>
        /// indicates if the item is selected
        /// </summary>
        private bool _isSelected;
        #endregion

        public SelectionItem(T element, bool isSelected)
        {
            Element = element;
            IsSelected = isSelected;
        }

        public SelectionItem(T element):this(element,false)
        {

        }

        #region public properties
        /// <summary>
        /// this UI-aware indicates if the element is selected or not
        /// </summary>
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
                }
            }
        }

        /// <summary>
        /// the element itself
        /// </summary>
        public T Element { get; set; }
        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
   }
1个回答

1

类似这样的东西应该能够提供您所需的:

<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="ListBoxItem">
            <CheckBox Content="{Binding Element.Region_Code}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

我一直在想如何定位 ListBoxItem 中的值。这看起来比我原来的方法要干净得多! - Rolan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接