2
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:myapp="clr-namespace:MyPlayer.Model"
    mc:Ignorable="d"
    x:Class="MyPlayer.VolumeButtons"
    x:Name="UserControl"
    d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <myapp:MusicPlayerModel x:Key="Model"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" DataContext="{StaticResource Model}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="35px"/>
            <ColumnDefinition Width="1.0*"/>
        </Grid.ColumnDefinitions>
        <Slider Value="{Binding Volume}" Margin="0,0,0,0" Grid.Column="1" VerticalAlignment="Center" x:Name="volumeSlider"/>
        <Button Margin="4,4,4,4" Content="Button" x:Name="muteButton" Click="MuteButton_Click"/>
    </Grid>
</UserControl>

现在的问题是,当我移动滑块时数据绑定工作正常(当我移动滑块时模型会更新)。

但是,当单击按钮时,我会更改模型中的值并期望它更新视图。

下面的代码:

private void MuteButton_Click(object sender, RoutedEventArgs e)
{
     musicPlayerModel.Volume = 0;
}

模型中的代码:

public double Volume
{
    get { return this.volume; }
    set 
    { 
         this.volume = value;
         this.OnPropertyChanged("SomeTestText");
         this.OnPropertyChanged("Volume");
    }
}

但在 OnPropertyChanged 中,该事件为空,因此没有任何反应。为什么事件为空而不是当我的滑块移动时以及如何解决它?

4

1 回答 1

3

您不应该直接调用该事件。您所做的是正确的,但前提是正确实现了 OnPropertyChanged 方法。在 Microsoft 推荐并在整个 BCL 中使用的模式中,OnPropertyChanged(和任何 OnXXXXEventName)应如下所示:

protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
    // get handler (usually a local event variable or just the event)
    if (this.PropertyChanged != null)
    {
        this.PropertyChanged(this, e);
    }
}

如果这是正确的,则您不必担心事件为 null 等。但是您的代码显示this.OnPropertyChanged("SomeTestText");这是不合法的。该字符串不是有效参数。根据事件模式,OnPropertyChanged 事件应如上所示,这意味着您应该按如下方式调用它:

this.OnPropertyChanged(new PropertyChangedEventArgs("Volume"));

注意:如果处理程序(事件)为空,则调用应用程序尚未注册到事件。通过代码,这可以用somevar.PropertyChanged += handlerMethod.


编辑:关于 Slider / WPF 和事件

在评论中,您建议它“应该”自动运行。但在上面的代码中,您OnPropertyChanged使用字符串调用。如前所述,这不是合法代码,因为 OnXXX 方法应该有一个继承自EventArgs. 尽管我在您的情况下考虑了一个正常的 PropertyChanged 事件,但 XAML 和 WPF 为另一种解释提供了空间(很抱歉现在才开始讨论)。

你(和我)在一件事上搞错了。MSDN的这句话解释说:

“请注意,有一个具有不同签名的同名 OnPropertyChanged 方法(参数类型是 PropertyChangedEventArgs),它可以出现在许多类上。OnPropertyChanged 用于数据对象通知,并且是 INotifyPropertyChanged 合同的一部分。”

您需要在覆盖 Volume 属性的代码中执行什么操作,您应该PropertyChangedCallback改为调用,或使用 OnXXX 代码,并将DependencyPropertyChangedEventArgs结构作为参数。如果您问我,即使您不使用原始 WPF 方法,您当前的方法也更容易;-)

于 2009-11-03T23:47:27.840 回答