简体   繁体   中英

WPF binding label content

Have a trouble with binding to label content

I have special custom TabControl in page. Bind SelectedTab property from page viewmodel to controlview model to get actualSelectedTab

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

For example, my tab control has 3 tabs; When tab one is selected - Selected Tab value is 0, etc.

But I need to show what current tab is selected in mainPage like 1/3 - 2/3 - 3/3

My final result must be like:

Selected Tab 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>

The problem is that you are not updating the UI in your property. You have to implement INotifyPropertyChanged in your ViewModel like this

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

You're Label should show now the SelectedTab (0, 1, 2, etc.). When you want do display eg 1/3 you should do this with an IValueConverter .

You need to implement 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
    }
}

And in your xaml change your binding like Content="{Binding SelectedTab, Converter={StaticResource MyConverter}, Mode=OneWay}

And in Window or UserControl add this in your resources to access the converter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM