WPF中bind使用
1、例TextBox的text關(guān)聯(lián)類的屬性
1.1、類的創(chuàng)建
class TestViewMode : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } public string show;//顯示 public string Show { get { return show; } set { show = value; PropertyChanged(this, new PropertyChangedEventArgs("Show")); } }
}
1.2、XAML代碼
<TextBox x:Name="textBox" Text="{Binding Path=Show, Mode=TwoWay}" />
1.3、關(guān)聯(lián)上下文
public partial class MainWindow : Window { TestViewMode vm =new TestViewMode(); public MainWindow() { this.DataContext = vm; } }
2、類中靜態(tài)變量在關(guān)聯(lián)主窗口中的TextBox、在另外的頁面中調(diào)用這個靜態(tài)變量
2.1、類的創(chuàng)建
class TestViewMode : INotifyPropertyChanged { // 定義靜態(tài)屬性值變化事件 public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; private static void OnStaticPropertyChanged([CallerMemberName] string propertyName = null) { OnStaticPropertyChanged(new PropertyChangedEventArgs(propertyName)); } private static void OnStaticPropertyChanged(PropertyChangedEventArgs e) { StaticPropertyChanged?.Invoke(null, e); } private static string property1; // 定義靜態(tài)屬性 public static string Property1 { get => property1; set { property1 = value; OnStaticPropertyChanged(); } } }
2.2、XAML代碼
<TextBox x:Name="textBox" Text="{Binding Path=Property1, Mode=TwoWay}" />
2.3、關(guān)聯(lián)上下文
public partial class MainWindow : Window
{
TestViewMode vm =new TestViewMode();
public MainWindow()
{
this.DataContext = vm;
}
}
2.4 在Page頁面直接調(diào)用
TestViewMode.Property1 = "xxxxxx";

浙公網(wǎng)安備 33010602011771號