WPF DataContext已更新,但UI未更新

时间:2013-12-15 00:26:43

标签: wpf user-interface binding datacontext

我有最大的简单应用程序。我想在按下按钮时填充列表框。我使用绑定,窗口DataContext在一些操作后更新,但是UI没有更新!

以下是代码:

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; }
    }
}

2 个答案:

答案 0 :(得分:0)

您需要支持财产变更通知。使用NuGet包管理器引用MVVM Lite项目,从ViewModelBase派生ViewModel,然后将链接属性更改为:

private string _link;
{
    public string link
    {
        get {return this._link;}
        set {this._link=value; RaisePropertyChanged(() => this.link); }
    }
}

您还需要为您的网址属性执行此操作,该属性需要公开才能使绑定正常工作。另外我知道这有点超出了问题的范围,但一般情况下你不应该使用像这样的Click处理程序,“正确”的方法是向你的ViewModel添加一个RelayCommand并将你的按钮的Command属性绑定到它。

答案 1 :(得分:0)

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

<强>视图模型:

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; }
    }

}

希望这有帮助,如果您有任何问题,请告诉我们!