Ale*_*ler 0 c# wpf xaml binding
绑定标签内容时遇到麻烦
我在页面中有特殊的自定义TabControl。将SelectedTab属性从页面ViewModel绑定到ControlView模型以获取ActualSelectedTab
public int SelectedTab
{
get { return _selectedTab; }
set
{
SetProperty(ref _selectedTab, value);
}
}
Run Code Online (Sandbox Code Playgroud)
例如,我的标签控件有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>
Run Code Online (Sandbox Code Playgroud)
问题在于您不更新属性中的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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您现在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
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的xaml中更改您的绑定,例如
Content="{Binding SelectedTab, Converter={StaticResource MyConverter}, Mode=OneWay}
并在您的资源中添加Window或UserControl添加此资源以访问转换器
<Window.Resources>
<local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7368 次 |
| 最近记录: |