我是wpf格式的新手,在项目结束时遇到了一个问题。假设我有一个顶部栏,有一个文本框和一个按钮。当用户单击该按钮时,此栏下的用户控件应使用文本框中的搜索结果进行更新,并且确实会进行更新,但它不会刷新UI,而只是刷新数据存储。为了简单起见,我将发布一个模拟该问题的演示代码,其中包含一个字符串属性。
<!-- the main window -->
<Window.DataContext>
<local:CustomerViewModel/>
</Window.DataContext>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Grid.Row="0">
<Label Content="content of the textbox: " Margin="10"/>
<TextBox Width="300" Text="{Binding Customer.Name}"/>
<Button Content="Update" Command="{Binding UpdateCommand}"/>
</StackPanel>
<DockPanel Grid.Row="1">
<local:TestControl />
</DockPanel>用户控件:
<!-- the user control named TestControl-->
<UserControl.DataContext>
<local:CustomerViewModel />
</UserControl.DataContext>
<DockPanel LastChildFill="True">
<Label DockPanel.Dock="Top" Content="Saved" />
<Label DockPanel.Dock="Bottom" Content="{Binding Info, UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>数据模型类:
public class Customer : ObservableObject
{
private string mName;
public string Name
{
get => mName;
set
{
if (value != mName)
{
mName = value;
OnPropertyChanged(nameof(Name));
}
}
}
}viewmodel类:
public class CustomerViewModel : ObservableObject
{
private Customer mCustomer;
public Customer Customer
{
get => mCustomer;
set
{
if (value != mCustomer)
{
mCustomer = value;
OnPropertyChanged(nameof(Customer));
}
}
}
private string mInfo;
public string Info
{
get => mInfo;
set
{
if (value != mInfo)
{
mInfo = value;
OnPropertyChanged(nameof(Info));
}
}
}
private ICommand mUpdateCommand;
public ICommand UpdateCommand
{
get
{
if (mUpdateCommand == null)
{
mUpdateCommand = new RelayCommand(p => SaveChanges());
}
return mUpdateCommand;
}
}
public void SaveChanges()
{
Info = Customer.Name + " was updated";
MessageBox.Show(Info);
}
public CustomerViewModel()
{
mCustomer = new Customer();
mCustomer.Name = "Test";
Info = mCustomer.Name;
}
}正确的值将显示在消息框中,但不会在用户控件中更改。我正在调用属性更改的接口,并尝试使用dispatcher.invoke调用按钮按下,同样的问题,我是否在这里遗漏了一些非常明显的东西?
发布于 2019-10-02 22:45:47
您的用户控件正在创建自己的视图模型的个人实例,并将其用于其DataContext。然后,该用户控件实例在其自身上设置Info,而不是在父窗口为其自己的datacontext设置的CustomerViewModel上。
<UserControl.DataContext>
<local:CustomerViewModel />
</UserControl.DataContext>从用户控件中删除这三行。将相应的行保留在窗口中。然后,用户控件将从其父控件继承其datacontext,并且它们将位于同一页面上。
这三行不仅声明视图使用的视图模型的类型;它们还创建类的实际实例并将其分配给DataContext。
https://stackoverflow.com/questions/58203846
复制相似问题