簡體   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