PropertyChangedEventHandler始终为null [英] PropertyChangedEventHandler always null

查看:161
本文介绍了PropertyChangedEventHandler始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚为什么PropertyChangedEventHandler始终为null。控件加载时,组合框包含正确的数据,每当第一个组合框的值发生更改时,就会调用RaisePropertyChanged方法,这会告诉我绑定是set属性。我错过了什么?







I can't figure out why the PropertyChangedEventHandler is always null. The combo boxes contain the correct data when the control loads, and the RaisePropertyChanged method is called whenever the first combo box's value is changed, which tells me that the binding is set property. What am I missing?



public class ModelNames : INotifyPropertyChanged
{
    // Get a list of available models by reflection
    private ObservableCollection<String> _modelList;
    private ObservableCollection<String> _modelProperties;

    public ModelNames()
    {
        SelectedModel = ModelList.FirstOrDefault();
    }

    private String _selectedModel;

    public String SelectedModel
    {
        get { return SelectedModel; }
        set
        {
            if (_selectedModel == value)
            {
                return;
            }
            _selectedModel = value;
            RaisePropertyChanged("SelectedModel");
            LoadModelResults(value);
        }
    }

    private void LoadModelResults(String modelName)
    {
        var types = GetType().Assembly.GetTypes();
        var modelType = types.FirstOrDefault(o => o.GetInterface("IModel") != null && o.Name == modelName);
        if (modelType != null)
        {
            ModelPropertyList =
                new ObservableCollection<String>(modelType.GetProperties().Select(o => o.Name).ToList());
        }

    }

    public ObservableCollection<String> ModelList
    {
        get
        {
            if (_modelList == null)
            {
                var types = GetType().Assembly.GetTypes();
                _modelList =
                    new ObservableCollection<string>(
                        types.Where(
                            o =>
                            o.GetInterface("IModel") != null && o.IsAbstract == false &&
                            o.Name.Contains("Rule") == false).Select(o => o.Name).ToList());
            }
            return _modelList;
        }
    }

    public ObservableCollection<String> ModelPropertyList
    {
        get { return _modelProperties; }
        set
        {
            if (_modelProperties == value)
            {
                return;
            }

            _modelProperties = value;
            RaisePropertyChanged("ModelPropertyList");
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }



XAML:




XAML:

<localView:BaseUserControl x:Class="Maximus.Pet.Views.UserControls.PetRuleBuilder"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

             xmlns:local="clr-namespace:Maximus.Pet.ViewModels"

             xmlns:localView="clr-namespace:Maximus.Pet.Views.UserControls"

                           xmlns:Models="clr-namespace:Maximus.Domain.Models;assembly=Maximus.Domain" mc:Ignorable="d" 

             d:DesignHeight="300" d:DesignWidth="300">


    <Grid removed="#814678AA" >

        <ComboBox ItemsSource="{Binding ModelNames}" SelectedItem="{Binding Path=SelectedModel,Mode=TwoWay}"

                Height="23" HorizontalAlignment="Left" Margin="44,27,0,0" Name="comboBoxModelNames" VerticalAlignment="Top" Width="120" 

                   SelectionChanged="comboBoxModelNames_SelectionChanged" d:DataContext="{d:DesignData }" />

        <ComboBox ItemsSource="{Binding ModelProperties}"

                Height="23" HorizontalAlignment="Left" Margin="44,57,0,0" Name="comboBoxModelProperties" VerticalAlignment="Top" Width="120" />

        

    </Grid>

</localView:BaseUserControl>





代码背后:





Code Behind:

 private readonly PetRulesViewModel _petRulesViewModel;
public PetRuleBuilder()
        {
            InitializeComponent();

            _petRulesViewModel = new PetRulesViewModel();
            
            DataContext = _petRulesViewModel;
        }

推荐答案

这是因为您从未向此事件的调用列表添加处理程序。它可以在C#代码中使用+ =运算符或在XAML中完成。我在你的代码中看不到这样的东西,而不是你展示的部分。我非常怀疑你从来没有这样做过。



这个MSDN示例会给你一个非常基本的想法:

http://msdn.microsoft.com/en-us/library/ms743596.aspx [ ^ ]。



但是,我几乎总是使用匿名方法,使用.NET v.3.5或更高版本,lambda语法:



This is because you never add a handler to the invocation list of this event. It can be done either using "+=" operator in C# code or in XAML. I cannot see anything like this in your code, not in the part you show. I seriously suspect you never did it.

This MSDN sample would give you the very basic idea:
http://msdn.microsoft.com/en-us/library/ms743596.aspx[^].

However, I nearly always use anonymous method and, with .NET v.3.5 or above, lambda syntax:

SomeEvent += (sender, eventArgs) => { SomeCode(); }





有很多理由可以做到这一点。



-SA


遇到同样的问题,我终于弄清楚.xaml文件中设置的datacontext不起作用(但不知道原因)。但是当我在后台.cs文件中设置页面datacontext

喜欢:

Meet the same problem,I finally figure out that the datacontext set in .xaml file doesn't work(yet dont know why).But when i set page datacontext in background .cs file
like:
this.datacontext = xxxx;





和PropertyChangedEventHandler事件obejct不再为null!



and the PropertyChangedEventHandler event obejct is not null anymore!


确实工作,而不是你想要的方式...例如:

It does work, just not the way that you want... for example:
<Window.DataContext>
    PetRulesViewModel
</Window.DataContext>



您可以在XAML树中的任何位置设置它,但是您设置得越深它,它将更加集中。它只是向前发展。即:上面的所有节点都无法看到设置的DataConext。


You can set it this way at any point in the XAML tree, but the deeper you set it, the more focused it will be. It's forward only. ie: all nodes above won't get visibility to the set DataConext.


这篇关于PropertyChangedEventHandler始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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