从ViewModel更改承载的Winform控件
本文关键字:Winform 控件 ViewModel | 更新日期: 2023-09-27 18:27:00
抱歉太老套了。。。但我对WPF和MVVM还很陌生,所以我不知道如何正确处理它。我的一个视图中有一个WinForms控件,当在ViewModel中引发事件时,我需要在它的代码后面修改它。我的视图的datacontext是继承的,因此视图模型没有在视图构造函数中定义。我该如何妥善处理这件事?我没有使用任何带有内置信使或聚合器的框架。我的相关代码如下。我需要从我的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}" />
ViewModel
private string screenVlcUrl;
public string ScreenVlcUrl
{
get { return screenVlcUrl; }
set
{
screenVlcUrl = value;
RaisePropertyChangedEvent("ScreenVlcUrl");
}
}
WPF在绑定属性时不执行属性setter,而是必须在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
}