簡體   English   中英

項目模板內的用戶控件的WPF更改通知不起作用

[英]WPF change notification of user control inside item template not working

我試圖將ObservableCollection<FilterControlViewmodel>中的每個視圖模型作為DataContextItemsControl的用戶控件FilterControl

綁定本身可以正常工作。 FilterControlViewmodel.FilterName正確顯示了"InitialFilterName" ,但是該屬性的任何更新都不會通知UI。

另外,向ObservableCollection<FilterControlViewmodel>添加元素也可以找到並添加其他用戶控件。 但是同樣, FilterControlViewmodel內部的值不會更新到UI。

任何有關缺少通知的提示都將不勝感激。 謝謝。

MainWindow.xaml

<Window.DataContext>
   <local:MainWindowViewmodel/>
</Window.DataContext>

<Grid>
   <ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
      <ItemsControl.ItemTemplate>
          <DataTemplate>
             <filter:FilterControl DataContext="{Binding}"></filter:FilterControl>
          </DataTemplate>
       </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>

FilterControl.xaml

<UserControl.DataContext>
   <local:FilterControlViewmodel/>
</UserControl.DataContext>

<Grid>
   <Label Grid.Column="0" Grid.Row="0" Content="{Binding FilterName}"></Label>
   <ComboBox Grid.Column="0" Grid.Row="1" ItemsSource="{Binding FilterValues}" SelectedItem="{Binding FilterValueSelected}"></ComboBox>
   <Button Grid.Column="1" Grid.Row="1" Content="X" Command="{Binding ResetFilterCommand}"></Button>
</Grid>

MainWindowViewmodel.cs

public class MainWindowViewmodel : INotifyPropertyChanged
{
   public FilterViewmodel FilterViewmodel
        {
            get => _filterViewmodel;
            set
            {
                if (Equals(value, _filterViewmodel)) return;
                _filterViewmodel = value;
                OnPropertyChanged();
            }
        }

FilterViewmodel.cs

public class FilterViewmodel : INotifyPropertyChanged
{
  public ObservableCollection<FilterControlViewmodel> FilterControls
        {
            get => return _filterControls;
            set
            {
                if (Equals(value, _filterControls)) return;
                _filterControls = value;
                OnPropertyChanged();
            }
        }

FilterControlViewmodel.cs

public class FilterControlViewmodel : INotifyPropertyChanged
{
   private string _filterName = "InitialFilterName";
   public string FilterName
   {
      get => _filterName;
      set
      {
         if (value == _filterName) return;
         _filterName = value;
         OnPropertyChanged();
      }
   }

您應刪除以下標記,因為它會創建FilterControlViewmodel另一個實例:

<UserControl.DataContext>
   <local:FilterControlViewmodel/>
</UserControl.DataContext>

然后, FilterControl將從ItemsControl的當前項目( FilterControlViewmodel )繼承其DataContext ,而無需顯式設置DataContext屬性:

<ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <filter:FilterControl/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM