【发布时间】:2020-01-04 22:22:14
【问题描述】:
我有一个 MainView,我在其中使用我创建的名为 VideoPlayer 的组件。 VideoPlayer 是一个 Grid,它有一个 MediaElement 以及一些按钮和一个滑块来控制视频播放。
我正在尝试通过将 VideoPlayer 中的属性绑定到 MainView 中的属性来设置要在 MainView 中播放的视频的路径。
相关部分代码如下:
来自 VideoPlayer.xaml 的片段:
<MediaElement
Name="MediaElement"
Grid.Row="0"
LoadedBehavior="Manual"
Stretch="Uniform"
Source="{Binding VideoLocation}" />
来自 VideoPlayer.xaml.cs 的片段:
public string VideoLocation
{
get { return (string)GetValue(VideoLocationProperty); }
set { SetValue(VideoLocationProperty, value); }
}
public static readonly DependencyProperty VideoLocationProperty
= DependencyProperty.Register("VideoLocation", typeof(string), typeof(VideoPlayer), new PropertyMetadata(null));
VideoPlayer用在MainView.xaml中,跟在MVVM后面:
<ReuseableComponents:VideoPlayer VideoLocation="{Binding VideoPath}"/>
这是 MainViewModel.cs 中的绑定属性 VideoPath:
private string _videoPath;
public string VideoPath
{
get => _videoPath;
set => SetProperty(ref _videoPath, value);
}
如果我删除 VideoLocation 绑定并在 MainView.xaml 中硬编码路径,视频将正常播放:
<ReuseableComponents:VideoPlayer VideoLocation="C:\Movies\FightClub.mp4"/>
所以,我认为问题在于 MainView 绑定而不是 VideoPlayer 绑定。
我在 MainView 中的所有其他属性绑定都有效,它们都遵循这种模式:
<ComponentName PropertyName="{Binding ViewModelPropertyName}">
其中 ViewModelPropertyName 在 MainView 中使用支持字段定义,并且 setter 调用 SetProperty()
编辑
我犯的错误是:在 VideoPlayer 的构造函数中,我有一行 DataContext = this; 我想我在某个教程的某个地方看到了它。无论如何,根据@Magnus 的建议,我删除了该行并将 VideoPlayer.xaml 更改为
<UserControl x:Name="TheControl" ...>
<Grid DataContext={Binding ElementName=TheControl} ...>
...
</Grid>
</UserControl>
以前 UserControl 没有设置 name 属性,而 Grid 没有设置 DataContext 属性。
【问题讨论】:
标签: c# wpf mvvm data-binding