WPF DataContext已更新,但UI未更新 [英] WPF DataContext updated but UI not updated

查看:90
本文介绍了WPF DataContext已更新,但UI未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有最多简单的应用.我想在按下按钮时填充列表框.我使用绑定,经过一些操作后窗口DataContext会更新,但UI不会更新!

I have maximum simple app. I want to fill listbox when button pressed. I use binding, window DataContext is updated after some operation, but UI not updated!

这是代码:

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Margin="432,288.04,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    <ListBox x:Name="urlsListBox" ItemsSource="{Binding Urls}" HorizontalAlignment="Left" Height="300" Margin="10,10,0,0" VerticalAlignment="Top" Width="417"/>

</Grid>

MainWindow.xaml.cs

    namespace WpfApplication1
{

    public partial class MainWindow : Window
    {
        ViewModel model = new ViewModel();

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = model;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            model.GetUrls();
        }
    }
}

ViewModel.cs

    namespace WpfApplication1
{
    class ViewModel
    {
        private ObservableCollection<Url> Urls { get; set; }

        public ViewModel()
        {
            Urls = new ObservableCollection<Url>();
        }

        public void GetUrls()
        {
            for (int i = 0; i < 5; i++)
            {
                Urls.Add(new Url { link = i.ToString() });
            }
        }
    }

    public class Url
    {
        public string link { get; set; }
    }
}

推荐答案

问题源于 ViewModel 类中的 Urls 属性.您需要公开 Urls ,否则MainWindow无法访问该属性:

Problem stems from the Urls property within the ViewModel class. You need to make Urls public, otherwise the MainWindow cannot access the property:

ViewModel:

namespace WpfApplication1
{
    public class ViewModel 
    {
        //make this public otherwise MainWindow will not have access to it!
        public ObservableCollection<Url> Urls { get; set; }

        public ViewModel()
        {
            Urls = new ObservableCollection<Url>();
        }

        public void GetUrls()
        {
            for (int i = 0; i < 5; i++)
            {
                Urls.Add(new Url { link = i.ToString() });
            }
        }
}

    public class Url
    {
         public string link { get; set; }
    }

}

希望这会有所帮助,如果您有任何疑问,请告诉我!

Hope this helps and let me know if you have any questions!

这篇关于WPF DataContext已更新,但UI未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆