【发布时间】:2025-12-20 14:55:07
【问题描述】:
我正在使用代码隐藏中的静态 Canvas.SetTop 方法更改 WPF 画布中 UIElement 的位置(在完整的应用程序中,我使用的是复杂的 Rx 链,但对于这个示例,我已经简化了点击按钮)。
我遇到的问题是 XAML 中的附加属性 Canvas.Top 的值绑定到我的 ViewModel 中的一个属性。调用 Canvas.SetTop 绕过了我的 ViewModel 中的 set,所以我没有得到更新的值。如何更新代码隐藏中的 Canvas.Top 值以便调用 ViewModel 属性的设置器?
XAML 视图:
<Window x:Class="WpfApplication1.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Grid>
<Canvas>
<Button Content="Move Button" Canvas.Top="{Binding ButtonTop}" Click="ButtonBase_OnClick" />
</Canvas>
</Grid>
</Window>
代码隐藏:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MainWindowView : Window
{
public MainWindowView()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Canvas.SetTop((UIElement) sender, Canvas.GetTop((UIElement) sender) + 5);
}
}
}
视图模型:
using System.Windows;
namespace WpfApplication1
{
public class MainWindowViewModel : DependencyObject
{
public static readonly DependencyProperty ButtonTopProperty = DependencyProperty.
Register("ButtonTop", typeof(int), typeof(MainWindowViewModel));
public int ButtonTop
{
get { return (int) GetValue(ButtonTopProperty); }
set { SetValue(ButtonTopProperty, value); }
}
public MainWindowViewModel()
{
ButtonTop = 15;
}
}
}
【问题讨论】:
-
使
ButtonTop绑定双向,如Canvas.Top="{Binding ButtonTop, Mode=TwoWay}"? -
添加
Mode=TwoWay并不能解决问题。干杯。