【问题标题】:WPF Bind different sources to comboboxWPF 将不同的源绑定到组合框
【发布时间】:2013-05-27 07:39:59
【问题描述】:

我有一个由文本框和组合框组成的用户控件。 我想要实现的是根据来自文本框的数据将组合框项目源绑定到不同的源。

例如:我有文本框输入:2 米,我希望组合框填充长度单位等。所以组合框的来源将基于文本框作为长度单位、质量等。

谁能帮我解决这个问题?

问候。

【问题讨论】:

    标签: wpf binding combobox


    【解决方案1】:

    好吧,我会使用另一种方法。坚持 MVVM 的东西怎么样?

    // class for all units you want to show in the UI
    public class MeasureUnit : ViewModelBase // base class implementing INotifyPropertyChanged
    {
        private bool _isSelectable;
        // if an item should not be shown in ComboBox IsSelectable == false
        public bool IsSelectable
        {
            get { return _isSelectable; }
            set
            {
                _isSelectable = value;
                RaisePropertyChanged(() => IsSelectable);
            }
        }
    
        private string _displayName;
        // the entry shown in the ComboBox
        public string DisplayName
        {
            get { return _displayName; }
            set
            {
                _displayName= value;
                RaisePropertyChanged(() => DisplayName);
            }
        }
    }
    

    现在我假设您有一个具有以下属性的虚拟机,它将用作DataContextComboBox

    private ObservableCollection<MeasureUnit> _units;
    public ObservableCollection<MeasureUnit> Units
    {
        get { return _units ?? (_units = new ObservableCollection<MeasureUnit>()); }
    }
    

    前端的用法可能是这样的。

    <ComboBox ItemsSource="{Binding Units}" DisplayMemberPath="DisplayName" ...>
        <ComboBox.Resources>
            <BooleanToVisibiltyConverter x:Key="Bool2VisConv" />
        </ComboBox.Resources>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding}" 
                     Visibility="{Binding IsSelectable, Converter={StaticResource Bool2VisConv}}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    

    现在您只需要实现一些逻辑,即设置Units 集合中项目的IsSelectable 属性。 ComboBox 只会显示 IsSelectable 设置为 true 的项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多