[英]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.