[英]WPF binding label content
绑定标签内容时遇到麻烦
我在页面中有特殊的自定义TabControl。 将SelectedTab属性从页面ViewModel绑定到ControlView模型以获取ActualSelectedTab
public int SelectedTab
{
get { return _selectedTab; }
set
{
SetProperty(ref _selectedTab, value);
}
}
例如,我的标签控件有3个标签; 选择选项卡一时-选定的选项卡值为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>
问题在于您不更新属性中的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}
并在Window
或UserControl
将此添加到您的资源中以访问转换器
<Window.Resources>
<local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.