[英]Binding to a static property is not responding to PropertyChanged
我對XAML和WPF相當陌生,並且閱讀了許多有關綁定控件屬性如何使用的示例,但似乎沒有一個適用於我的問題。
我有一個繼承了INotifyPropertyChanged的靜態類Analyze
下面的代碼摘要
class Analyse : INotifyPropertyChanged
{
public static DataSet moodleData; // Dataset containing the log data for analysis
private static bool dataPresent = true;
public static Boolean DataPresent
{
get { return dataPresent; }
set
{
if (dataPresent != value)
{
dataPresent = value;
NotifyStaticPropertyChanged("DataPresent");
}
}
}
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged
= delegate { };
private static void NotifyStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
#endregion
public static void clearData()
{
try
{
moodleData.Clear();
DataPresent = false;
}
catch { }
}
}
我的XAML包含本地名稱空間
<Window x:Name="TheMainWindow" x:Class="MoodleLogAnalyse.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
xmlns:local="clr-namespace:MoodleLogAnalyse"
Title="MainWindow" Height="556.88" Width="793" WindowStartupLocation="CenterScreen">
並且按鈕正確綁定
<Button Name="OpenButton" Command="Open"
IsEnabled="{Binding Source={x:Static local:Analyse.DataPresent},
Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Content="Open Grades" />
該屬性絕對綁定到IsEnabled,在代碼中手動更改dataPresent定義可啟用和禁用按鈕,但是動態更改(例如在true和false之間切換)(例如調用clear data方法)不會在運行時更改按鈕的IsEnabled狀態。時間。
當我插入要檢查的斷點時,屬性更改事件正在觸發。
我看不出我要怎么做! 任何幫助,將不勝感激。
Source
屬性用於存儲將用作備用綁定源的對象(默認情況下,綁定使用DataContext
)。
<Button IsEnabled="{Binding Source={x:Static local:Analyze.DataPresent}}" />
因此,當您使用上面的代碼時, Static
擴展DataPresent
提供DataPresent
屬性的當前值,並且該值存儲在Source
屬性中。 在這種情況下,綁定使用裝箱的常量值( true
或false
)作為源。
<Button IsEnabled="{Binding Path=(local:Analyze.DataPresent)}" />
但是,當您指定Path
屬性時,綁定將找到您的靜態類並綁定到該屬性。 在這種情況下,靜態DataPresent
屬性是源,而StaticPropertyChanged
事件用於通知綁定有關更新。
如果綁定到靜態屬性,則不能使用INotifyPropertyChanged
因為沒有實例可用於訪問該屬性。 必須改用相應的靜態事件。
事件的名稱必須等於StaticPropertyChanged
並且其類型必須為EventHandler<PropertyChangedEventArgs>
。 或名稱必須由兩部分組成:屬性名稱和后綴Changed
。 在后一種情況下,事件的類型必須為EventHandler
因為事件僅通知有關相應屬性的更改。
這意味着:
Analyze
類可以是靜態的,因為不需要INotifyPropertyChanged
。 StaticPropertyChanged
重命名為DataPresentChanged
並將其類型更改為EventHandler
。 換一種說法:
public static class Analyze
{
public static DataSet moodleData; // Dataset containing the log data for analysis
private static bool dataPresent = true;
public static Boolean DataPresent
{
get { return dataPresent; }
set
{
if (dataPresent != value)
{
dataPresent = value;
DataPresentChanged(null, EventArgs.Empty);
}
}
}
public static event EventHandler DataPresentChanged = delegate { };
}
有用的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.