很抱歉是陈词滥调...但我对WPF和MVVM都很陌生,所以我不确定如何正确处理这个问题。我在其中一个视图中有一个WinForms控件,当我在ViewModel中引发一个事件时,我需要修改它的代码。我继承了我的视图的datacontext,因此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");
}
}
答案 0 :(得分:0)
绑定属性时,WPF不会执行属性设置器,而是必须在DependencyProperty声明中定义一个Callback方法:
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
}