-1

我有一堂这样写的课

public class AudioPlayer : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    [...]
    private static AudioPlayer instance = new AudioPlayer();

    public static AudioPlayer Instance { get { return instance; } }

    private Track currentTrack = null;

    // the pointer to the current track selected
    // it is useful to retrieve its new position when playlist got updates
    public Track CurrentTrack { get { return currentTrack; } 
        private set 
        { 
            currentTrack = value;
            NotifyPropertyChanged();
        } 
    }
    public class Track : ICloneable
    {
            public string Title { get; set; }
    }

这是xml:

    <StackPanel DataContext="{Binding Source={x:Static audiocontroller:AudioPlayer.Instance}}">
        <Label Name="lbl_bind" Content="{Binding CurrentTrack.Title}"></Label>
        <Button Name="btn" Click="btn_Click" Height="20" ></Button>
    </StackPanel>

并且代码有效!

现在我希望使用 ModelView 控制器来组建 AudioPlayer。这个怎么做 ?

4

1 回答 1

0

假设“AudioPlayer”是您的“ViewModel”,您可以这样实现:

<UserControl x:Class="YourNamespace.AudioPlayerView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:YourNamespace">

    <UserControl.DataContext>
        <local:AudioPlayer/>
    </UserControl.DataContext>

    <StackPanel>
        <Label Name="lbl_bind" Content="{Binding CurrentTrack.Title}"></Label>
        <Button Name="btn" Click="btn_Click" Height="20" ></Button>
    </StackPanel>
</UserControl>

我建议避免命名控件,除非您实际上是在编写代码隐藏(对于 MVVM,这应该是不必要的)。我还建议从“Click”处理程序切换到“Command”处理程序,并使用“DelegateCommand”之类的东西来处理按钮事件。

于 2014-02-13T06:10:48.103 回答