0

我有这样的 wfp 表格:

public partial class MediaPlayerControlMain : Window
{
    MediaPlayerMain MediaPlayerMain;

    public MediaPlayerControlMain()
    {
        MediaPlayerMain = new MediaPlayerMain();
        InitializeComponent();
    }
}

我有使用 MediaPlayerMain 对象的用户控件(播放列表)。该用户控件具有:

public partial class PlayList : UserControl
{
    public MediaPlayerMain MediaPlayer
    {
        get { return (MediaPlayerMain)GetValue(MediaPlayerProperty); }
        set { SetValue(MediaPlayerProperty, value); }
    }

    public static readonly DependencyProperty MediaPlayerProperty =
        DependencyProperty.Register(
            "MediaPlayer", typeof(MediaPlayerMain), typeof(PlayList),
            new FrameworkPropertyMetadata()
        );

}

有没有办法只使用 xaml 设置 MediaPlayer 属性。我尝试使用“{Binding ElementName=MediaPlayerMain}”,但似乎 MediaPlayerMain 尚未初始化。虽然我在 InitializeComponent() 函数之前对其进行了初始化。我究竟做错了什么?。将此对象传递给我的用户控件的最佳选择是什么?

4

3 回答 3

1

您需要在标记中命名您的根元素(Window/UserControl 本身)。IE:

<Window x:Name="mediaPlayer"
    ....>
    <TextBlock Text="{Binding SomeProperty,ElementName=mediaPlayer}"
于 2013-01-16T12:53:42.117 回答
1
public partial class MediaPlayerControlMain : Window,INotifyPropertyChanged
    {


        public MediaPlayerControlMain()
        {                
            InitializeComponent();
            MediaPlayerMain = new MediaPlayerMain();
        }
        private MediaPlayerMain mediaPlayerMain;

        public MediaPlayerMain MediaPlayerMain
        {
            get { return mediaPlayerMain; }
            set { mediaPlayerMain = value; Notify("MediaPlayerMain"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Notify(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));

        }
    }

 "{Binding MediaPlayerMain RelativeSource={RelativeSource AncestorType=Window}}"

问题是您试图绑定字段而不是属性。因为绑定源必须是属性而不是字段,因为绑定系统使用反射并且只查找属性而不是字段。我希望这会有所帮助。

于 2013-01-16T13:11:02.767 回答
0

我没有看到您设置DataContext任何地方,并且我认为您MediaPlayerMain的 XAML 树中没有命名的对象

当您编写时{Binding ElementName=MediaPlayerMain},您是在告诉 WPF 将属性设置为等于名为 Visual Tree 的 XAML 对象MediaPlayerMain

相反,您可能正在寻找的是绑定到名为 DataContext 的属性MediaPlayerMain,在这种情况下,您的绑定将如下所示:

<local:PlayList MediaPlayer="{Binding MediaPlayerMain}" />

但这将不起作用,除非将您DataContext设置为包含该属性的对象MediaPlayerMain,例如this.DataContext = this在 Window 的构造函数中设置。

作为替代方案,您可以ElementName在绑定中使用来告诉 WPF 在 Visual Tree 中而不是DataContextWindow.

<local:MediaPlayerControlMain x:Name="MainWindow" ...>
    <local:PlayList MediaPlayer="{Binding MediaPlayerMain, ElementName=MainWindow}" />
</local:MediaPlayerControlMain>

这将使您的绑定MediaPlayerMain在名为 的 XAML 元素中查找属性,该元素MainWindow是您的MediaPlayerControlMain类。

如果您不熟悉 WPF 的 DataBinding,实际上我的博客上有一篇专门针对初学者的文章,可以帮助您更好地理解它是什么以及它是如何工作的:您所说的“DataContext”是什么?

于 2013-01-16T13:51:12.787 回答