Mag*_*agB 2 c# wpf binding properties
我正在学习关于属性绑定的wpf c#.我创建了一个简单的wpf应用程序.我尝试将矩形控件的宽度绑定到后面的代码中的属性"PageWidth".但不知何故它不起作用(视图不会得到属性的更改).我想要实现的目标: - 矩形的宽度在代码后面用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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码中存在两个问题:
DataContext,所以绑定没有引用(它不知道它应该从哪个对象获取PageWidth属性)PageWidth不是依赖项属性,也不会引发PropertyChanged事件,因此在值更改时无法通知绑定系统.要解决这些问题,您应该:
将DataContext设置为窗口本身:
// in the constructor
DataContext = this;
Run Code Online (Sandbox Code Playgroud)使MainWindow类实现INotifyPropertyChanged接口,并更改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");
}
}
}
...
Run Code Online (Sandbox Code Playgroud)