wpf WPF如何刷新用户控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25438857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:24:13  来源:igfitidea点击:

WPF How to refresh a user control

c#wpf

提问by Kokombads

I tried UIElement.InvalidateVisualbut it didn't work. I read about this INotifyPropertyChangedbut I don't know exactly how it is used, not to mention I'm talking about User Controls, it seems I need to use that INotifyPropertyChangedto all of the controls.

我试过了,UIElement.InvalidateVisual但没有用。我读过这个,INotifyPropertyChanged但我不知道它是如何使用的,更不用说我在谈论用户控件,似乎我需要将它INotifyPropertyChanged用于所有控件。

I'm having trouble refreshing combo boxes changes and data grid changes, what I did is to close and reopen the form but I don't want that approach because it seems sluggish in re-executing every user control constructors.

我在刷新组合框更改和数据网格更改时遇到问题,我所做的是关闭并重新打开表单,但我不想要这种方法,因为重新执行每个用户控件构造函数似乎很缓慢。

this is my code:

这是我的代码:

if (linkSource.ToString() == "BreedList.xaml")
{
    this.InvalidateVisual();
}
else if (linkSource.ToString() == "PetTypeList.xaml")
{
    this.InvalidateVisual();
}
else if (linkSource.ToString() == "IrritantList.xaml")
{
    this.InvalidateVisual();
}

回答by Sheridan

This answer is an attempt to give you a peek into how WPF applications work, but I am notoffering to teach you WPF... that is yourjob.

这个答案试图让您了解 WPF 应用程序的工作原理,但我不会教您 WPF……这是您的工作。

As @HighCore correctly pointed out, there is no UserControl.Refreshmethod. In a WPF Application (using MVVM), we create custom class objects called view models that contain the data and functionality that the UserControls and/or Windows (called views) need to provide. They are paired by setting the view DataContextproperty to an instance of the relevant view model. There are several ways to do that... this is just one way:

正如@HighCore 正确指出的那样,没有UserControl.Refresh方法。在 WPF 应用程序(使用 MVVM)中,我们创建称为视图模型的自定义类对象,其中包含UserControls 和/或Windows(称为视图)需要提供的数据和功能。它们通过将 viewDataContext属性设置为相关视图模型的实例来配对。有几种方法可以做到这一点……这只是一种方法:

public SomeView()
{
    ...
    DataContext = new SomeViewModel();
}

Now, all of the controls declared in SomeViewhave access to all of the (public) properties and ICommands from the SomeViewModelclass. We use them with data binding:

现在,在 中声明的所有控件SomeView都可以访问类中的所有 ( public) 属性和ICommands SomeViewModel。我们将它们与数据绑定一起使用:

<TextBox Text="{Binding SomePropertyInSomeViewModel}" ... />  

...

...

<ListBox ItemsSource="{Binding SomeCollectionPropertyInSomeViewModel}" />  

During initialisation of the SomeViewModelclass, we might see something like this:

SomeViewModel类的初始化过程中,我们可能会看到如下内容:

public SomeViewModel()
{
    SomeCollectionPropertyInSomeViewModel = SomeDataSource.GetSomeCollection();
}

This gets the data from any external data source and populates the SomeCollectionPropertyInSomeViewModelproperty. In turn, the SomeCollectionPropertyInSomeViewModelproperty provides the collection items for the ListBox. So finally, to answer your question, How do we refresh the data?, the answer is to call the methods that get the data again. So you could do something like this:

这从任何外部数据源获取数据并填充SomeCollectionPropertyInSomeViewModel属性。反过来,该SomeCollectionPropertyInSomeViewModel属性为 提供了集合项ListBox。最后,回答你的问题,我们如何刷新数据?,答案是再次调用获取数据的方法。所以你可以做这样的事情:

public void RefreshData()
{
    SomeCollectionPropertyInSomeViewModel = SomeDataSource.GetSomeCollection();
}

Ok, so here ends today's lesson. For any further questions, please refer to the proper Microsoft documentation on MSDN. For follow up information, please see the Introduction to WPFpage on MSDN.

好了,今天的课程到此结束。如有任何其他问题,请参阅 MSDN 上相应的 Microsoft 文档。有关后续信息,请参阅MSDN上的 WPF 简介页面。

回答by norekhov

To add to previous answer: there are two ways to create "SomeViewModel". In both ways it should notify about a property change.

添加到先前的答案:有两种方法可以创建“SomeViewModel”。在这两种方式中,它都应该通知属性更改。

1) Use a DependencyObject. This is a standard WPF way, all UserControls are also DependencyObjects. Taken from here, read full explanation: http://wpftutorial.net/DependencyProperties.html

1) 使用依赖对象。这是一个标准的 WPF 方式,所有的 UserControls 也是 DependencyObjects。取自此处,阅读完整说明:http: //wpftutorial.net/DependencyProperties.html

    public class SomeViewModel : DependencyObject
    {
        // Dependency Property
        public static readonly DependencyProperty CurrentTimeProperty =
             DependencyProperty.Register("CurrentTime", typeof(DateTime),
             typeof(SomeViewModel), new FrameworkPropertyMetadata(DateTime.Now));

        // .NET Property wrapper
        public DateTime CurrentTime
        {
            get { return (DateTime)GetValue(CurrentTimeProperty); }
            set { SetValue(CurrentTimeProperty, value); }
        }
    }

When CurrentTime changes everybody which is registered ( for example using {Binding CurrentTime} in XAML ) will get a notification and "Refresh"

当 CurrentTime 更改注册的每个人(例如在 XAML 中使用 {Binding CurrentTime} )时,将收到通知并“刷新”

2) Use INotifyPropertyChanged interface. Here's a small example: http://msdn.microsoft.com/en-us/library/vstudio/ms229614(v=vs.100).aspx

2) 使用 INotifyPropertyChanged 接口。这是一个小例子:http: //msdn.microsoft.com/en-us/library/vstudio/ms229614(v=vs.100).aspx

There are some differences between this approaches ( for example you can't create binding toINotifyPropertyChanged property ). Please read here: http://www.codeproject.com/Articles/62158/DependencyProperties-or-INotifyPropertyChangedINotifyPropertyChanged vs. DependencyProperty in ViewModel

这种方法之间存在一些差异(例如,您不能创建INotifyPropertyChanged 属性的绑定)。请在此处阅读:http: //www.codeproject.com/Articles/62158/DependencyProperties-or-INotifyPropertyChanged INotifyPropertyChanged 与 ViewModel 中的 DependencyProperty

Good luck!

祝你好运!