嗨,我完全是WPF的新手,我希望能够通过CS文件中的变量控制XAML中任何内容的边距值,我已经阅读了几个问题/ stackoverflow上的答案,试图实现它,但它似乎工作。
这是我到目前为止所尝试过的,但我无法以某种方式让它工作,真的需要就此提出建议。
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Thickness _Margin = new Thickness(100, 20, 0, 0);
public Thickness Margin
{
get { return _Margin; }
set
{
_Margin = value;
//Notify the binding that the value has changed.
this.OnPropertyChanged("Margin");
}
}
public MainWindow()
{
InitializeComponent();
No.DataContext = _Margin;
}
protected void OnPropertyChanged(string strPropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
XAML:
<Window x:Class="WpfApplication1.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 Name="No">
<Border BorderBrush="Silver" BorderThickness="1" Height="100" HorizontalAlignment="Left" Margin="{Binding _Margin}" Name="border1" VerticalAlignment="Top" Width="200" />
</Grid>
</Window>
答案 0 :(得分:2)
属性名称&#34;公共厚度保证金&#34;存在问题。你使用它是覆盖Window.Margin属性,你应该重命名它。其次,您绑定的是成员值而不是属性值。
试试这段代码(我添加了一个触发PropertyChanged事件的按钮,无论你想使用什么,都应该替换它):
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Thickness _margin = new Thickness(100, 20, 0, 0);
public Thickness GridMargin
{
get { return _margin; }
set
{
_margin = value;
//Notify the binding that the value has changed.
this.OnPropertyChanged("GridMargin");
}
}
public MainWindow()
{
InitializeComponent();
No.DataContext = this;
}
protected void OnPropertyChanged(string strPropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Random r = new Random();
GridMargin = new Thickness(r.Next(0, 100));
}
}
XAML:
<Grid Name="No">
<Border BorderBrush="Silver" BorderThickness="1" Height="100" HorizontalAlignment="Left" Margin="{Binding GridMargin}" Name="border1" VerticalAlignment="Top" Width="200" />
<Button Content="Margin" HorizontalAlignment="Right" VerticalAlignment="Bottom" Click="ButtonBase_OnClick"></Button>
</Grid>
答案 1 :(得分:0)
您设置数据上下文的方式不一致。 DataContext
被设置为“MainWindow”的“_Margin”属性,但绑定也是以“_Margin”为目标。你需要这个:
No.DataContext = this;