2013-03-06 117 views
0

我用ProgressBarLabel创建了UserControl如何使用MVVM数据绑定WPF更新多个用户控件实例?

<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的多个实例,并从代码更新ProgressBar后面使用MVVM。但我无法弄清楚这一点。我是否需要针对UserControl有一个ViewModel,以便每个实例都有自己的ViewModel副本。

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

感谢&问候, 巴拉特

+0

ElementName应指向x:Name属性值,而不是元素类型(UserControl,TextBox等) – Will 2013-03-07 13:44:38

回答

1

如果我理解你正确的,这听起来像什么,你要创建一个视图模型为这个UserControl,然后有一个视图模型的多个实例(一个用于在UserControl的每个实例风景)。如果您有一个绑定了多个UserControls的ViewModel,它们都会显示完全相同的内容。

这听起来像你已经有一个视图模型的页面,这样你就可以简单地为UserControl添加视图模型作为页面视图模型的属性,如:

public class PageViewModel : INotifyPropertyChanged 
{ 
    private UCViewModel _ucViewModel; 

    //Other ViewModel Code 

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

哪里UCViewModel是视图模型为您的UserControl。然后,在你的XAML,只需结合于UCViewModel的属性,就像这样:

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

如果你有UCViewModels的集合,你需要不同的方式处理了一点,但概念仍然是一样。

+0

感谢您的回答。这正是我想要做的。我有并行运行任务,并试图通过用户控制显示每个任务的进度(UC包含标签和进度栏)。我会尝试您的解决方案,然后将其更新为解决方案。 – Jasti 2013-03-06 23:46:38