如何使用MVVM数据绑定WPF更新多个用户控件实例?

时间:2013-03-06 19:35:20

标签: wpf mvvm wpf-controls

我创建了UserControl ProgressBarLabel

<Label Content="{Binding ElementName=UserControl, Path=StatusProperty}" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="76,0,0,32" Name="lblStatus" VerticalAlignment="Bottom" Grid.RowSpan="2" />
<ProgressBar Grid.Row="2" Height="20" HorizontalAlignment="Left" Margin="12,3,0,0" Name="pbCheckProgress" Style="{DynamicResource ProgressBarStyle}" Maximum="{Binding ElementName=UserControl, Path=MaximumProperty}" Minimum="{Binding ElementName=UserControl, Path=MinimumProperty}" Value="{Binding ElementName=UserControl, Path=ValueProperty}" VerticalAlignment="Top" Width="156" />

然后我创建了以下DependencyProperties

// Dependency Properties for labels
public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status", typeof(string), typeof(UserControl1), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

// Dependency Properties for progress bar properties
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(UserControl1), new FrameworkPropertyMetadata(0.0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(UserControl1), new FrameworkPropertyMetadata(0.0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(UserControl1), new FrameworkPropertyMetadata(0.0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

现在我想在同一页面中创建此UserControl的多个实例,并使用MVVM从后面的代码更新ProgressBar。但我无法弄清楚这一点。我是否需要为UserControl创建一个ViewModel,以便每个实例都有自己的ViewModel副本。

有没有办法从ViewModel页面更新所有实例?

谢谢&amp;问候, 巴勒特

1 个答案:

答案 0 :(得分:1)

如果我理解你的内容,听起来你想要为这个UserControl创建一个ViewModel,然后拥有该ViewModel的多个实例(一个用于View上UserControl的每个实例) 。如果你有一个绑定了多个UserControls的ViewModel,它们都会显示完全相同的东西。

听起来你已经有了View的ViewModel,所以你可以简单地将UserControl的ViewModel添加为Page ViewModel的属性,如下所示:

public class PageViewModel : INotifyPropertyChanged
{
    private UCViewModel _ucViewModel;

    //Other ViewModel Code

    public UCViewModel UserControlViewModel
    {
        get { return _ucViewModel; }
    }
}

其中UCViewModel是UserControl的ViewModel。然后,在您的XAML中,您只需绑定到UCViewModel上的属性,如下所示:

<local:myControl Status="{Binding UserControlViewModel.Status}"... />

如果您有一系列UCViewModel,您需要稍微改变一下,但概念仍然相同。