我正在研究WPF中的约束力
我想将Button.IsEnabled属性绑定到Class1的属性; Button.IsEnabled = c1.Property。事实上,Textblock.Text按照我的意图改变,但Button.IsEnabled没有改变。
这是我的代码:
[MainWindow.xaml.cs]
using System.Windows;
namespace WpfApp2
{
public partial class MainWindow : Window
{
public static Class1 c1 { get; set; }
public MainWindow()
{
InitializeComponent();
c1 = new Class1();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
c1.Property = !c1.Property;
textblock.Text = c1.Property.ToString();
}
}
}
[MainWindow.xaml]
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="150,137,0,0" VerticalAlignment="Top" Width="75" IsEnabled="{Binding Property, Source={x:Static local:MainWindow.c1}}"/>
<Button Content="Button2" HorizontalAlignment="Left" Margin="271,137,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<TextBlock x:Name="textblock" HorizontalAlignment="Left" Margin="150,177,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
</Grid>
</Window>
[的Class1.cs]
namespace WpfApp2
{
public class Class1
{
public bool Property { get; set; }
}
}
怎么了?我无法猜测......我能在代码中完成吗?请帮帮我!
答案 0 :(得分:3)
您需要在INotifyPropertyChanged
中实施Class1
界面,并在PropertyChanged
值更改时提升其Property
事件:
namespace WpfApp2
{
public class Class1 : INotifyPropertyChanged
{
private bool property = false;
public bool Property
{
get { return property; }
set { if (value != property) { property = value; RaisePropertyChanged(); } }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName);
}
}