我試圖控制的可視性綁定到一個全局變量:UWP窗口10能見度綁定到一個全局變量
我有能見度轉換器:
public class BooleanToVisibilityConverter : IValueConverter
{
public bool IsReversed { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
我還創建了一個類,自DependencyObject繼承:
public class Verified : DependencyObject
{
public static readonly DependencyProperty VerifiedUserNameProperty = DependencyProperty.Register(
"VerifiedUserName",
typeof(string),
typeof(Verified),
new PropertyMetadata(string.Empty)
);
public string VerifiedUserName
{
get { return (string)GetValue(VerifiedUserNameProperty); }
set { SetValue(VerifiedUserNameProperty, value); }
}
public static readonly DependencyProperty IsVerifiedProperty = DependencyProperty.Register(
"IsVerified",
typeof(bool),
typeof(Verified),
new PropertyMetadata(false, new PropertyChangedCallback(IsVerifiedChanged))
);
public bool IsVerified
{
get { return (bool)GetValue(IsVerifiedProperty); }
set { SetValue(IsVerifiedProperty, value); }
}
private static void IsVerifiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Verified container = d as Verified;
bool latestIsVerifiedValue = (bool)e.NewValue;
if (latestIsVerifiedValue == true)
{
//To Do
}
}
}
在我的App.xaml
我創建變量:
public static Verified myValidator = new Verified();
public static BooleanToVisibilityConverter myConverter = new BooleanToVisibilityConverter();
在一個簡單的頁面中,我添加了一個文本框,並且我想將它的可見性綁定到myValidator變量。
爲了實現這個目標,我在代碼中創建綁定:
Binding myBinding = new Binding();
myBinding.Source = App.myValidator;
myBinding.Path = new PropertyPath("IsVerified");
myBinding.Mode = BindingMode.OneWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
myBinding.Converter = App.myConverter;
BindingOperations.SetBinding(txtName2, VisibilityProperty, myBinding);
在App.xaml中:我設置我的驗證的價值是這樣的:
App.myValidator.IsVerified = false;
當我導航到簡單頁面的文本框不可見(OK)。
爲了測試行爲,我在屏幕上添加了一個按鈕,並添加了代碼以更改myValidator.isVerified的值。
當我更改我的App.myValidator.IsVerified的值時,文本框的可見性不會改變。我該如何解決這個問題?
嘗試在轉換器設置斷點,看看如果它實際上受到打擊。我懷疑它不是。 –
它第一次到達轉換器。我更改IsVerified的值時驗證器的propertyChange事件始終正確執行。但在第一次轉換器沒有再被擊中之後。 – user1282441
不知道這是否會這樣做,但也嘗試從'INotifyPropertyChanged'繼承並實現它,然後看它是否有效。 –