【问题标题】:How to add XAML property value using the ViewModel?如何使用 ViewModel 添加 XAML 属性值?
【发布时间】:2020-10-01 01:34:52
【问题描述】:

我想在单击按钮后更改 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;

可能缺少什么?

【问题讨论】:

  • 什么是View.MyDialog?这是ViewModel 类还是支持类?
  • 你的 ViewModel 绑定代码是什么?
  • @cahyo,这是我的 XAML 类

标签: c# xaml viewmodel


【解决方案1】:

我将推荐您的第一个解决方案,因为它会破坏 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;

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多