INotifyPropertyChanged 不适用于 UserControl

问题描述 投票:0回答:1

[注意:这是来自专有代码,所以我重命名了变量、函数......我可能忘记了一些,请告诉我]

我使用组合框从列表中选择数据,更新 SharedViewModel 值

Label 组件已更新,但我的 UserControlTest 组件未更新

我希望 UserControlTest 显示来自 SharedViewModel 的更新值

没有任何变化,就像 UserControlTest 未更新一样

  • 我在 UserControlTest 用户控件上强制使用 DataContext

  • 我重命名了 UserControlTest 本地属性以避免名称重叠

  • 我使用了Binding Debugging,没发现什么问题

    <ComboBox SelectionChanged="DataTestChanged" >
      ...                                    
      <TextBlock Text="{Binding Path=SomeData, Source={StaticResource SharedViewModelInstance}, Mode=TwoWay, Converter={StaticResource SomeDataToStringConverter }}" />
      ...
    </ComboBox>
    
    <Label Content="{Binding Path=SomeData, Source={StaticResource SharedViewModelInstance}, Mode=OneWay}"/>
    
    <userControls:UserControlTest x:Name="dataSelector" 
                            SomeData2="{Binding Path=SomeData, Source={StaticResource SharedViewModelInstance}, Mode=OneWay}"
                            DataContext="{StaticResource SharedViewModelInstance}"
                            ></userControls:DataSelector >
    

如果我修改同一 DataContext/Parent 中另一个组件的数据,PropertyChanged 就会被触发

private DataType _SomeData = new DataType();
public DataType SomeData
{
    get
    {
        return _SomeData;
    }
    set
    {
        _SomeData = value;
        OnPropertyChanged(nameof(SomeData));
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    //PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

我尝试在UserComponent中显示本地数据和共享数据

从组合中选择其他内容时,它们都没有改变

<UserControl ...> <UserControl.Resources> <main:SharedViewModel x:Key="SharedViewModelInstance"/> </UserControl.Resources> <Border Style="{StaticResource SomePanel}"> <StackPanel x:Name="somePanel" Height="Auto" Orientation="Vertical" > <!--displays global value from shared model view--> <Label Content="{Binding Path=SomeData, Source={StaticResource SharedViewModelInstance}, Mode=TwoWay}"/> <!--displays local data--> <Label Content="{Binding Path=SomeData2, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </StackPanel> </Border>

背后的代码

public partial class UserControlTest: UserControl { public static readonly DependencyProperty SomeData2Property = DependencyProperty.Register("SomeData2", typeof(DataType), typeof(UserControlTest)); public DataType SomeData2 { get { return (DataType)GetValue(SomeData2Property); } set { SetValue(SomeData2Property, value); } }
    
c# wpf data-binding
1个回答
0
投票
这不能在 UserControl 中使用,因为它不使用主实例而是创建一个新实例

<UserControl.Resources> <main:SharedViewModel x:Key="SharedViewModelInstance"/> </UserControl.Resources>
很混乱,因为 main 中声明的看起来像这样

<local:SharedViewModel x:Key="SharedViewModelInstance"/>
    
© www.soinside.com 2019 - 2024. All rights reserved.