[英]How to call method in window (.xaml.cs) from viewmodel (.cs) without introducing new references in wpf
[英]access string that is declared in xaml.cs from viewmodel - wpf
我如何从视图模型访问xaml.cs中声明的变量的值。
String strFileName = path.Text.ToString();
可以说这在我的xaml.cs中,我想在ViewModel中使用strFileName。
怎么样?
提前致谢
编辑(代码):
我的UserControl(Page1):
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"));
}
}
我假设您是新手,如果您已经知道其中的某些或大部分,那就太好了,那就继续学习吧。
将视图和视图模型连接在一起的通常方法是绑定。 每当您考虑将视图连接到视图模型时,这应该是您的第一个候选人。
要绑定,您需要一个依赖项属性。 他们需要一个依赖对象。 您的用户控件是其中之一,因此您可以使用它。
有时将依赖对象用作视图模型可能会很有用,但我认为您的vm将是普通类(poco)。
您可以轻松地向视图添加依赖项属性。 有一个propdp代码段。 这将为您提供常规的依赖项属性。 那会起作用,但是在它们上设置绑定有点尴尬,所以我可能会使用附加的依赖项属性。
仔细阅读它们。 我建议您还对常规的非附加依赖项属性进行一些试验,看看执行我建议的操作时会发生什么。
在视图的代码后面添加您的依赖项属性。
这是我自己的一个。 这不是字符串,因为我想鼓励您自己探索这个问题,而不是粘贴一些解决方案。(而且我可以使用这种方法粘贴到现有代码中。)
public static readonly DependencyProperty IsDraggingPieceProperty = DependencyProperty.RegisterAttached(
"IsDraggingPiece",
typeof(bool),
typeof(MainWindow),
new FrameworkPropertyMetadata(false
, new PropertyChangedCallback(IsDraggingPieceChanged)
));
私有静态无效IsDraggingPieceChanged(DependencyObject d,DependencyPropertyChangedEventArgs e){//我在这里做东西}
公共静态无效SetIsDraggingPiece(UIElement元素,布尔值){element.SetValue(IsDraggingPieceProperty,value); } public static bool GetIsDraggingPiece(UIElement element){return(bool)element.GetValue(IsDraggingPieceProperty); }
注意,这使用寄存器Attached 。
然后,您可以将其绑定到XAML中。 在视图的开始标记中,可以使用dp:
local:MainWindow.IsDraggingPiece="{Binding IsDraggingPiece}"
然后,它将绑定到我在viewmodel中拥有的IsDraggingPiece属性。 上面有通常的绑定选项,例如您可以将其设置为mode = twoway。 dp的meta选项之一使其默认使用双向。 由于您将为此设置值,并且您不想覆盖过多的绑定,因此请使用这些方法中的任一种来使绑定变得双向并且更难以覆盖。 如果您使用setcurrentvalue,则不会覆盖绑定,但我更喜欢使用mode = twoway表示意图。 这样,它是双重安全的。
如果要在多种视图中使用这种绑定,则可以选择定义附加的依赖项属性。
在后面的代码中,您可以在该附加属性上设置值。 为此使用setcurrentvalue。
this.SetCurrentValue(MainWindow.IsDraggingPieceProperty, true);
您可以将变量存储在依赖项属性本身中,也可以在视图中存储其他私有变量,然后从那里设置dp值。 哪个最好取决于您在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.