我正在学习有关属性绑定(bind)的 wpf c#。我创建了一个简单的 wpf 应用程序。我尝试将矩形控件的宽度绑定(bind)到代码后面的属性“PageWidth”。但不知何故它不起作用( View 没有得到属性的变化)。 我想要实现的目标: - 矩形的宽度在后面的代码中被初始化为 100 - 如果单击“width++”按钮,矩形的宽度将逐步增加 10。 我是否遗漏了我的代码中的某些内容?请提出建议并随时修改我的代码。提前致谢。
XAML:
<Window x:Class="MyWpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle
Fill="#FF6262BD"
HorizontalAlignment="Left"
Margin="23,24,0,0"
Stroke="Black"
VerticalAlignment="Top"
Width="{Binding Path=PageWidth}"
Height="100" />
<Button
Content="Width++"
HorizontalAlignment="Left"
Margin="35,129,0,0"
VerticalAlignment="Top"
Width="75"
Click="Button_Click" />
</Grid>
xaml.cs:
using System;
using System.Windows;
namespace MyWpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PageWidth = 100;
}
private Int32 _pageWidth;
public Int32 PageWidth
{
get
{
return _pageWidth;
}
set
{
if ( _pageWidth != value )
{
_pageWidth = value;
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if ( PageWidth <= 200 )
{
PageWidth += 10;
}
}
}
}
最佳答案
你的代码有两个问题:
- 您没有设置
DataContext
,因此绑定(bind)没有引用(它不知道应该从哪个对象获取PageWidth
属性) PageWidth
不是依赖属性,不会引发PropertyChanged
事件,因此当值更改时无法通知绑定(bind)系统。
要解决这些问题,您应该:
将 DataContext 设置为窗口本身:
// in the constructor DataContext = this;
使
MainWindow
类实现INotifyPropertyChanged
接口(interface),并更改PageWidth
属性,使其引发PropertyChanged
事件:public partial class MainWindow : Window, INotifyPropertyChanged { ... public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } private Int32 _pageWidth; public Int32 PageWidth { get { return _pageWidth; } set { if ( _pageWidth != value ) { _pageWidth = value; OnPropertyChanged("PageWidth"); } } } ...
关于C# WPF : View doesn't get the changes of property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203976/