2017-03-24 9 views
0

ラベル内容へのバインドに問題がありますWPFバインディングラベルの内容

私は特別なカスタムTabControlをページに持っています。例えばactualSelectedTab

public int SelectedTab 
    { 
     get { return _selectedTab; } 
     set 
     { 
      SetProperty(ref _selectedTab, value); 
     } 
    } 

を取得するためにモデルをcontrolviewするページのviewmodelからバインドSelectedTabプロパティ、私のタブコントロールには、3つのタブがあります。タブ1が選択されている場合 - 選択したタブ値はなど、

0であるしかし、私は現在のタブが1/3のようにメインページで選択されているかを示す必要がある - 3分の2〜3分の3

私の最終的な結果必要がありますことのように:

選択したタブ1/3 ...

<Label 
            Margin="5 0 28 0" 
      VerticalAlignment="Stretch" 
      HorizontalAlignment="Stretch" 
      TextElement.FontSize="12" 
      TextElement.FontWeight="Bold" 
      TextElement.Foreground="White" 
      VerticalContentAlignment="Center" 
      Content="{Binding SelectedTab, Mode=OneWay}"> 


            </Label> 

答えて

4

問題3/3はあなたがあなたの財産でUIを更新していないことです。あなたはLabelは今SelectedTab(0、1、2、など)を表示する必要があります。この

public class ViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string name) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

    public int SelectedTab 
    { 
     get { return _selectedTab; } 
     set 
     { 
      SetProperty(ref _selectedTab, value); 
      OnPropertyChanged("SelectedTab"); 
     } 
    } 
} 

ようなあなたのViewModelにINotifyPropertyChangedのを実装する必要があります。あなたが表示したいときなど1/3あなたはIValueConverterでこれを行う必要があります。あなたはあなたの Content="{Binding SelectedTab, Converter={StaticResource MyConverter}, Mode=OneWay}

のように結合し、WindowUserControlにコンバータに

<Window.Resources> 
    <local:MyConverter x:Key="MyConverter"/> 
</Window.Resources> 
+0

にアクセスするには、あなたのリソースにこれを追加変更IValueConverter

public class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var tabIndex = int.Parse(value.ToString()); return tabIndex + 1; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //don't needed } } 

そして、あなたのXAMLでを実装する必要が

私のViewModelは、INotiifyPropetryChangedを実装するMainViewModelの子であり、 d 0,1,2は完璧に動作します。 IValueConverterの使用例を教えてもらえますか? –

+0

私の答えを更新しました –

関連する問題