powered by simpleCommunicator - 2.0.56     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Binding и INotifyPropertyChanged
4 сообщений из 4, страница 1 из 1
Binding и INotifyPropertyChanged
    #38654052
Roman Mejtes
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
имею след. класс:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
    public class Person : INotifyPropertyChanged
    {
        private readonly int _key;
        public int Key
        {
            get { return _key; }
        }
        public string Name { set; get; }
        public string Surname { set; get; }
        public int Age { set; get; }
        public Person(int key)
        {
            _key = key;
        }
        public override string ToString()
        {
            return string.Format("{0} {1} (age: {2})", Name, Surname, Age);
        }
        protected void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }

класс совершенно обычный, создан для теста, так же существует класс со списком ObservableCollection<Person> и
вьюха в виде DataGrid'а
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
<DataGrid Grid.Row="1" ItemsSource="{Binding PeopleView}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Key" Binding="{Binding Key}" Width="Auto" SortMemberPath="Key" CanUserSort="True"/>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <my:TextBlockEx Text="{Binding Name}" Blue="{Binding Blue}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Surname" Binding="{Binding (my:Person.Surname)}" Width="*"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="Auto"/>
            </DataGrid.Columns>
        </DataGrid>


Проблема вся в том, что когда в биндинге колонки (например: Binding="{Binding Key}") я указываю {Binding (my:Person.Key)} программа при запуске выдает исключение Argumnt Null Exceptoin "Key cannot be null." Но, если я убирают наследование интерфейса INotifyPropertyChanged ошибки не возникает. Проще говоря ошибка возникает только тогда, когда я наследую интерфейс.
С чем это связано?
...
Рейтинг: 0 / 0
Binding и INotifyPropertyChanged
    #38654059
Сон Веры Павловны
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Roman MejtesС чем это связано?
С тем, что запись вида {Binding (my:Person.Key)} задает для биндинга возврат значения attached property Key, зарегистрированной в public static классе Person, а вовсе не возврат поля Key класса Person. Что там происходит дальше - нужно смотреть по стектрейсу.
И да, зачем здесь INPC, если нигде не вызывается PropertyChanged?
...
Рейтинг: 0 / 0
Binding и INotifyPropertyChanged
    #38654064
Roman Mejtes
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Сон Веры Павловны,

Это просто пример, по этому вызов метода отсутствует, но он погоду не делает.
Но если я не наследую интерфейс всё же работает и значения свойства класса Person нормально биндится..
...
Рейтинг: 0 / 0
Binding и INotifyPropertyChanged
    #38654091
Сон Веры Павловны
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Roman Mejtes,

во-первых, при упоминании ошибок следует приводить стектрейс. Выглядит он примерно так:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
   в System.Collections.Specialized.HybridDictionary.get_Item(Object key)
   в System.ComponentModel.PropertyChangedEventManager.PrivateAddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
   в System.ComponentModel.PropertyChangedEventManager.AddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
   в MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
   в MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
   в MS.Internal.Data.ClrBindingWorker.AttachDataItem()
   в System.Windows.Data.BindingExpression.Activate(Object item)
   в System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   в System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   в MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   в MS.Internal.Data.DataBindEngine.Run(Object arg)
   в MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   в System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   в System.Windows.ContextLayoutManager.UpdateLayout()
   в System.Windows.UIElement.UpdateLayout()
   в System.Windows.Interop.HwndSource.SetLayoutSize()
   в System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   в System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
   в System.Windows.Window.SetRootVisual()
   в System.Windows.Window.SetRootVisualAndUpdateSTC()
   в System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   в System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   в System.Windows.Window.CreateSourceWindowDuringShow()
   в System.Windows.Window.SafeCreateWindowDuringShow()
   в System.Windows.Window.ShowHelper(Object booleanBox)
   в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   в System.Windows.Threading.DispatcherOperation.InvokeImpl()
   в System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   в System.Threading.ExecutionContext.runTryCode(Object userData)
   в System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   в System.Windows.Threading.DispatcherOperation.Invoke()
   в System.Windows.Threading.Dispatcher.ProcessQueue()
   в System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   в System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   в System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   в System.Windows.Application.RunDispatcher(Object ignore)
   в System.Windows.Application.RunInternal(Window window)
   в System.Windows.Application.Run(Window window)
   в System.Windows.Application.Run()
   в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   в System.Threading.ThreadHelper.ThreadStart()

Во-вторых, если связываемый класс реализует INPC, то фреймворк на рантайме устанавливает свои обработчики событий.
В-третьих, биндинги вычисляются на рантайме через рефлекшн. Если фреймворк видит, что компонент реализует INPC, то следует попытка вычислить биндинг, и к результату привязать INPC. Биндинг в данном случает возвращает пустую ссылку на экземпляр, следует попытка привязки обработчика - и ArgumentNullException.
В-четвертых, не нужно забивать гвозди пассатижами - они предназначены не для этого. Используйте обычный синтаксис привязки свойств, если у вас эти свойства - не attached.
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Binding и INotifyPropertyChanged
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]