如何使用 ViewModel 添加 XAML 属性 值?

How to add XAML property value using the ViewModel?

我想在单击按钮后更改 UI 一侧的内容。假设单击按钮后更改按钮宽度。

<Button x:Name="btnButt" Content="Button"/>

然后在我的 ViewModel 中,

View.MyDialog mydialog = new View.MyDialog();
mydialog.btnButt.Width = 3000;

但是,一切都不起作用。我还尝试绑定来自 ViewModel 的字符串:

\ XAML
<Button x:Name="btnButt" Content="Button" Width="{Binding WidthVM}"/>

\ ViewModel
public int WidthVM = 3000;

可能缺少什么?

不会推荐你的第一个解决方案,因为它会破坏 MVVM 的目的。

您的第二个解决方案实际上是正确的,即绑定来自 VM 的一些数据。它不起作用,因为您需要以 MVVM 方式将其发送到 UI 的信号更改,像这样:

public const string WidthVMPropertyName = "WidthVM";

private int _widthVM = 0;

public int WidthVM
{
    get
    {
        return _widthVM;
    }
    set
    {
        Set(WidthVMPropertyName, ref _widthVM, value);
    }
}

\ then set it like:


WidthVM = 3000;