WPF绑定标签内容

时间:2017-03-24 14:16:43

标签: c# wpf xaml binding

绑定到标签内容时遇到问题

我在页面中有特殊的自定义TabControl。将SelectedTab属性从页面视图模型绑定到controlview模型以获取actualSelectedTab

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

例如,我的标签控件有3个标签;选择选项卡1时 - 选定选项卡值为0等

但是我需要显示在mainPage中选择的当前选项卡,如1/3 - 2/3 - 3/3

我的最终结果必须是:

选择标签1/3 ... 3/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>

1 个答案:

答案 0 :(得分:5)

问题是您没有更新属性中的UI。您必须在ViewModel中实现INotifyPropertyChanged,如此

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");
        }
    }
}

Label现在应该显示SelectedTab(0,1,2等)。如果你想要显示例如1/3你应该使用IValueConverter

您需要实施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中更改你的绑定  Content="{Binding SelectedTab, Converter={StaticResource MyConverter}, Mode=OneWay}

WindowUserControl中添加此资源以访问转换器

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