2013-05-27 44 views
0

我有一個由文本框和組合框組成的用戶控件。 我想實現的是根據文本框中的數據將組合框項目源綁定到不同的源。WPF將不同的來源綁定到組合框

例如:我有文本框輸入:2米,我想組合框填充長度單位等。所以組合框的來源將基於文本框中的長度單位,質量等。

任何人都可以幫我解決這個問題嗎?

問候。

回答

0

那麼我會用另一種方法。那些堅持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