【问题标题】:Alter hosted Winform control from ViewModel从 ViewModel 更改托管的 Winform 控件
【发布时间】:2013-08-08 20:58:20
【问题描述】:

对不起,陈词滥调......但我对 WPF 和 MVVM 还很陌生,所以我不确定如何正确处理这个问题。我的一个视图中有一个 WinForms 控件,当在 ViewModel 中引发事件时,我需要在其背后的代码中进行修改。我的视图的数据上下文是继承的,因此视图模型未在视图构造函数中定义。我将如何正确处理这个问题?我没有使用任何带有内置信使或聚合器的框架。我的相关代码如下。我需要从我的 ViewModel 中触发 ChangeUrl 方法。

编辑:根据 HighCore 的建议,我更新了我的代码。但是,我仍然无法执行 ChangeUrl 方法,该事件正在我的 ViewModel 中引发。需要做哪些修改??

UserControl.xaml

<UserControl ...>
    <WindowsFormsHost>
        <vlc:AxVLCPlugin2 x:Name="VlcPlayerObject" />
    </WindowsFormsHost>
</UserControl>

UserControl.cs

public partial class VlcPlayer : UserControl
{
    public VlcPlayer()
    {
        InitializeComponent();
    }

    public string VlcUrl
    {
        get { return (string)GetValue(VlcUrlProperty); }
        set
        {
            ChangeVlcUrl(value);
            SetValue(VlcUrlProperty, value);
        }
    }

    public static readonly DependencyProperty VlcUrlProperty =
            DependencyProperty.Register("VlcUrl", typeof(string), typeof(VlcPlayer), new PropertyMetadata(null));

    private void ChangeVlcUrl(string newUrl)
    {
        //do stuff here
    }
}

view.xaml

<wuc:VlcPlayer VlcUrl="{Binding Path=ScreenVlcUrl}" />

视图模型

private string screenVlcUrl;
public string ScreenVlcUrl
{
    get { return screenVlcUrl; }
    set
    {
        screenVlcUrl = value;
        RaisePropertyChangedEvent("ScreenVlcUrl");
    }
}

【问题讨论】:

  • winforms 不支持 MVVM。您必须在需要完成此操作的任何地方保留对 View 的引用,或者使用 EventAggregator 或类似的东西。
  • @HighCore - 感谢您的建议。我已经进行了建议的更改,但是它仍然无法正常运行。我错过了什么?

标签: c# wpf


【解决方案1】:

当您绑定属性时,WPF 不会执行您的属性设置器,而是必须在 DependencyProperty 声明中定义回调方法:

public string VlcUrl
{
    get { return (string)GetValue(VlcUrlProperty); }
    set { SetValue(VlcUrlProperty, value); }
}

public static readonly DependencyProperty VlcUrlProperty =
        DependencyProperty.Register("VlcUrl", typeof(string), typeof(VlcPlayer), new PropertyMetadata(null, OnVlcUrlChanged));

private static void OnVlcUrlChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var player = obj as VlcPlayer;
    if (obj == null)
       return;

    obj.ChangeVlcUrl(e.NewValue);
}

private void ChangeVlcUrl(string newUrl)
{
    //do stuff here
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2010-11-27
  • 2012-09-04
相关资源
最近更新 更多