WPF将不同的源绑定到combobox

WPF将不同的源绑定到combobox,wpf,binding,combobox,Wpf,Binding,Combobox,我有一个由文本框和组合框组成的用户控件。 我试图实现的是基于文本框中的数据将组合框项目源绑定到不同的源 例如:我有文本框输入:2米,我想用长度单位填充组合框,以此类推。因此,组合框的来源将基于文本框,如长度单位、质量等 有人能帮我弄清楚吗 问候 我会用另一种方法。那么坚持MVVM的东西呢 // class for all units you want to show in the UI public class MeasureUnit : ViewModelBase // base class

我有一个由文本框和组合框组成的用户控件。 我试图实现的是基于文本框中的数据将组合框项目源绑定到不同的源

例如:我有文本框输入:2米,我想用长度单位填充组合框,以此类推。因此,组合框的来源将基于文本框,如长度单位、质量等

有人能帮我弄清楚吗


问候

我会用另一种方法。那么坚持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);
        }
    }
}
现在,我假设您有一个具有以下属性的VM,它将用作
组合框的
DataContext

private ObservableCollection<MeasureUnit> _units;
public ObservableCollection<MeasureUnit> Units
{
    get { return _units ?? (_units = new ObservableCollection<MeasureUnit>()); }
}
私有可观测采集单元;
公共可观测收集单位
{
获取{return\u units???(\u units=newobservetecollection());}
}
前端的用法可能如下所示

<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
属性。
组合框
仅显示项目,其中
IsSelectable
设置为
true