访问从viewmodel在xaml.cs中声明的字符串 - wpf

时间:2018-04-18 07:32:13

标签: c# wpf mvvm

如何访问xaml.cs中声明的变量值(来自viewmodel)。

String strFileName = path.Text.ToString();


假设这是在我的xaml.cs中,我想在我的ViewModel中使用strFileName。
如何?

提前致谢

编辑(代码):

我的UserControl(第1页):

 public static readonly DependencyProperty productsStringProperty = DependencyProperty.RegisterAttached(
    "productsString", typeof(string), typeof(Page1),
    new FrameworkPropertyMetadata()
    {
        PropertyChangedCallback = OnproductsStringChanged,
        BindsTwoWayByDefault = true
    });
    private static void OnproductsStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    { }

    public static void SetproductsString(UIElement element, String value) { element.SetValue(productsStringProperty, value); }
    public static String GetproductsString(UIElement element) { return (String)element.GetValue(productsStringProperty); }

XAML:

             views:Page1.productsString="{Binding productsString}"

然后我打电话:

String paths = products.Text.ToString();
this.SetCurrentValue(productsStringProperty,paths);

然后我的VM:

 private string _products;

    public string Products
    {
        get { return _products; }
        set
        {
            _products = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Products"));
        }
    }

1 个答案:

答案 0 :(得分:0)

我假设你对这些东西不熟悉,如果你已经知道其中的一些或大部分内容那么好,只需继续过去。

将视图和视图模型连接在一起的常用方法是绑定。每当您考虑将视图连接到视图模型时,这应该是您的第一个候选人 要绑定,您需要一个依赖属性。它们需要依赖对象。您的用户控件就是其中之一,因此您可以使用它 偶尔使用依赖项对象作为视图模型可能很有用,但我假设您的虚拟机将成为普通类(poco)。
您可以非常轻松地向视图添加依赖项属性。有一个propdp片段。这会给你一个常规的依赖属性。这样可行但是对它们设置绑定有点尴尬所以我可能会使用附加的依赖属性。
仔细阅读它们。 我建议你也尝试一下常规的非附加依赖属性,看看当你做我建议的时候会发生什么。

在后面的视图代码中添加您的依赖项属性 这是我自己的一个。这不是一个字符串,因为我想鼓励你自己探索,而不是粘贴一些解决方案。(而且我可以粘贴现有代码,我就是这样。)

public static readonly DependencyProperty IsDraggingPieceProperty = DependencyProperty.RegisterAttached(
        "IsDraggingPiece",
        typeof(bool),
        typeof(MainWindow),
        new FrameworkPropertyMetadata(false
      , new PropertyChangedCallback(IsDraggingPieceChanged)
    ));

private static void IsDraggingPieceChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) {     //我在这里做的东西 }

public static void SetIsDraggingPiece(UIElement element,bool value) {     element.SetValue(IsDraggingPieceProperty,value); } public static bool GetIsDraggingPiece(UIElement element) {     return(bool)element.GetValue(IsDraggingPieceProperty); }

请注意,这使用了附加寄存器。

然后,您可以在XAML中绑定它。在视图的开始标记中,您可以使用dp:

local:MainWindow.IsDraggingPiece="{Binding IsDraggingPiece}"

然后将绑定到我的viewmodel中的IsDraggingPiece属性。有通常的绑定选项就像你可以使它模式= twoway。 dp的一个元选项默认使用twoway。由于您要设置此值并且您不想过度编写绑定,因此请使用其中任何一种方法来使绑定更加困难并且更难以写入。如果你使用setcurrentvalue它不会超过写绑定,但我更喜欢通过使用mode = twoway来表示意图。这样它就更加安全了。

如果要在多个视图中使用此类绑定,也可以定义附加的依赖项属性。

在您的代码中,您可以在该附加属性上设置值。为此使用setcurrentvalue。

this.SetCurrentValue(MainWindow.IsDraggingPieceProperty, true);

您可以将变量存储在依赖项属性本身或视图中的其他私有变量中,并从那里设置dp值。哪个最好取决于你正在做什么。