通过控制边框来移动图像
本文关键字:移动 图像 边框 控制 | 更新日期: 2023-09-27 18:16:24
嗨,我完全是新的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>
您使用的属性名称"公共厚度边界"存在问题,它覆盖了窗口。属性,你应该重命名它。其次,您绑定的是成员值而不是属性值。
试试下面的代码(我添加了一个按钮来触发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>
设置数据上下文的方式不一致。DataContext
被设置为"MainWindow"的"_Margin"属性,但随后绑定也针对路径"_Margin"。你需要的是这个:
No.DataContext = this;