繁体   English   中英

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

[英]How to update multiple instances of user control using MVVM databinding WPF?

我创建了一个带有ProgressBarLabelUserControl

<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更新所有实例?

谢谢与问候,巴拉特

如果我正确理解您的话,听起来您想为此UserControl创建一个ViewModel,然后拥有该ViewModel的多个实例(对于View上每个UserControl实例,一个实例)。 如果您有一个ViewModel绑定了多个UserControls ,则它们都将显示完全相同的内容。

听起来您已经有了Page的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}"... />

如果您有UCViewModels的集合,则需要以不同的方式处理它,但是概念仍然相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM