【问题标题】:WPF binding label contentWPF 绑定标签内容
【发布时间】:2017-03-24 14:16:42
【问题描述】:

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

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

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

例如,我的选项卡控件有 3 个选项卡; When tab one is selected - Selected Tab value is 0, etc.

但我需要显示在 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>

【问题讨论】:

    标签: c# wpf xaml binding


    【解决方案1】:

    问题是您没有更新资源中的 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>
    

    【讨论】:

    • 我的 ViewModel 是实现 INotiifyPropetryChanged 的​​ MainViewModel 的子级,是的,0,1,2 完美。你能给我一个使用 IValueConverter 的例子吗,也许这是我需要的?
    • 更新了我的答案
    猜你喜欢
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多