在 DataTemplate 中使用时,行为 DependencyProperty 不会更新 ViewModel 附加信息

如何解决在 DataTemplate 中使用时,行为 DependencyProperty 不会更新 ViewModel 附加信息

我在 DependencyProperty 中有一个 Behavior,我正在为 OnAttached() 设置值。

然后我使用 DependencyPropertyMode 将视图模型属性绑定到此 OneWayToSource

由于某种原因,OneWayToSource 绑定在 DataTemplate 内完成时不会更新绑定的视图模型属性(视图模型的 setter 永远不会被调用)。在其他情况下,它似乎工作正常。

我没有收到任何绑定错误,也看不到任何异常等迹象,我不知道我做错了什么。

WPF 设计器确实会显示一些错误,声称是 The member "TestPropertyValue" is not recognized or is not accessibleThe property "TestPropertyValue was not found in type 'TestBehavior',具体取决于您查看的位置。我不确定这些是否是“真正的”错误(正如我观察到的,WPF 设计器在始终显示真正的问题方面似乎并不完全可靠),如果是,它们是否与此问题或其他问题完全相关.

如果这些设计器错误确实与这个问题有关,我只能假设我一定是错误地声明了 DependencyProperty。如果是这种情况,我将无法看到错误在哪里。

我制作了一个复制该问题的示例项目。以下代码应该足够了,可以添加到任何名为 WpfBehaviorDependencyPropertyIssue001 的新 WPF 项目中。

主窗口.xaml
<Window x:Class="WpfBehaviorDependencyPropertyIssue001.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:tb="clr-namespace:WpfBehaviorDependencyPropertyIssue001.Behaviors"
        xmlns:vm="clr-namespace:WpfBehaviorDependencyPropertyIssue001.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vm:MainViewModel />
    </Window.DataContext>
    <StackPanel>
        <Label Content="{Binding TestPropertyValue,ElementName=OuterTestA}" Background="Cyan">
            <b:Interaction.Behaviors>
                <tb:TestBehavior x:Name="OuterTestA" TestPropertyValue="{Binding MainTestValueA,Mode=OneWayToSource}" />
            </b:Interaction.Behaviors>
        </Label>
        <Label Content="{Binding MainTestValueA,Mode=OneWay}" Background="Orange" />
        <Label Content="{Binding MainTestValueB,Mode=OneWay}" Background="MediumPurple" />
        <DataGrid ItemsSource="{Binding Items}" RowDetailsVisibilityMode="Visible">
            <b:Interaction.Behaviors>
                <tb:TestBehavior x:Name="OuterTestB" TestPropertyValue="{Binding MainTestValueB,Mode=OneWayToSource}" />
            </b:Interaction.Behaviors>
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <StackPanel>
                        <Label Content="{Binding TestPropertyValue,ElementName=InnerTest}" Background="Cyan">
                            <b:Interaction.Behaviors>
                                <tb:TestBehavior x:Name="InnerTest" TestPropertyValue="{Binding ItemTestViewModelValue,Mode=OneWayToSource}" />
                            </b:Interaction.Behaviors>
                        </Label>
                        <Label Content="{Binding ItemTestViewModelValue,Mode=OneWay}" Background="Lime" />
                    </StackPanel>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>
    </StackPanel>
</Window>
TestBehavior.cs
using Microsoft.Xaml.Behaviors;
using System.Windows;

namespace WpfBehaviorDependencyPropertyIssue001.Behaviors
{
    public class TestBehavior : Behavior<UIElement>
    {
        public static DependencyProperty TestPropertyValueProperty { get; } = DependencyProperty.Register("TestPropertyValue",typeof(string),typeof(TestBehavior));

        // Remember,these two are just for the XAML designer (or I guess if we manually invoked them for some reason).
        public static string GetTestPropertyValue(DependencyObject dependencyObject) => (string)dependencyObject.GetValue(TestPropertyValueProperty);
        public static void SetTestPropertyValue(DependencyObject dependencyObject,string value) => dependencyObject.SetValue(TestPropertyValueProperty,value);

        protected override void OnAttached()
        {
            base.OnAttached();
            SetValue(TestPropertyValueProperty,"Example");
        }
    }
}
ViewModelBase.cs
using System.ComponentModel;

namespace WpfBehaviorDependencyPropertyIssue001.ViewModels
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }
    }
}
MainViewModel.cs
using System.Collections.ObjectModel;

namespace WpfBehaviorDependencyPropertyIssue001.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        public ObservableCollection<ItemViewModel> Items
        {
            get => _Items;
            set
            {
                _Items = value;
                OnPropertyChanged(nameof(Items));
            }
        }
        private ObservableCollection<ItemViewModel> _Items;

        public MainViewModel()
        {
            Items = new ObservableCollection<ItemViewModel>()
            {
                new ItemViewModel() { ItemName="Item 1" }
            };
        }

        public string MainTestValueA
        {
            get => _MainTestValueA;
            set
            {
                System.Diagnostics.Debug.WriteLine($"Setting {nameof(MainTestValueA)} to {(value != null ? $"\"{value}\"" : "null")}");
                _MainTestValueA = value;
                OnPropertyChanged(nameof(MainTestValueA));
            }
        }
        private string _MainTestValueA;

        public string MainTestValueB
        {
            get => _MainTestValueB;
            set
            {
                System.Diagnostics.Debug.WriteLine($"Setting {nameof(MainTestValueB)} to {(value != null ? $"\"{value}\"" : "null")}");
                _MainTestValueB = value;
                OnPropertyChanged(nameof(MainTestValueB));
            }
        }
        private string _MainTestValueB;
    }
}
ItemViewModel.cs
namespace WpfBehaviorDependencyPropertyIssue001.ViewModels
{
    public class ItemViewModel : ViewModelBase
    {
        public string ItemName
        {
            get => _ItemName;
            set
            {
                _ItemName = value;
                OnPropertyChanged(nameof(ItemName));
            }
        }
        private string _ItemName;

        public string ItemTestViewModelValue
        {
            get => _ItemTestViewModelValue;
            set
            {
                System.Diagnostics.Debug.WriteLine($"Setting {nameof(ItemTestViewModelValue)} to {(value != null ? $"\"{value}\"" : "null")}");
                _ItemTestViewModelValue = value;
                OnPropertyChanged(nameof(ItemTestViewModelValue));
            }
        }
        private string _ItemTestViewModelValue;
    }
}

预期调试输出消息(不包括标准 WPF 消息):

Setting MainTestValueA to null
Setting MainTestValueA to "Example"
Setting MainTestValueB to null
Setting MainTestValueB to "Example"
Setting ItemTestViewModelValue to null
Setting ItemTestViewModelValue to "Example"

实际调试输出消息(不包括标准 WPF 消息):

Setting MainTestValueA to null
Setting MainTestValueA to "Example"
Setting MainTestValueB to null
Setting MainTestValueB to "Example"
Setting ItemTestViewModelValue to null

解决方法

我完全测试了你的代码,它运行良好。

您的调试运行良好,因为在创建 MainViewModel 的实例时会立即调用所有成员。

MainTestValueA 以 null 值调用,然后调用 OnPropertyChanged 并使用 bind 属性调用标签控件的 TestPropertyValue 和 {{ 1}} 方法初始化 OnAttached 并将其打印在输出上。

example 的相同步骤 对 MainTestValueB 重复相同的步骤,但因为它位于 ItemTestViewModelValue 内,DataGridView 不允许从 View 访问。

当然,这是我的结论。

,

我已经设法解决了这个问题。

出于某种原因,UpdateSourceTrigger 中的 PropertyChangedDataTemplate 的绑定似乎需要 ModeOneWayToSource。 这样做会导致正确更新视图模型属性。

我通过实验发现了这一点,我不确定为什么这种行为与在 DataTemplate 之外完成的绑定不同,尽管这种行为可能记录在某处。

如果我能找到这种行为的原因(记录与否),我将使用该信息更新此答案。

附加信息

为了让未来的读者更清楚,带有 OneWayToSource 绑定 outside 的标签按预期工作。用于此的 XAML(来自原始问题)如下所示:

DataTemplate

但是, <Label Content="{Binding TestPropertyValue,ElementName=OuterTestA}" Background="Cyan"> <b:Interaction.Behaviors> <tb:TestBehavior x:Name="OuterTestA" TestPropertyValue="{Binding MainTestValueA,Mode=OneWayToSource}" /> </b:Interaction.Behaviors> </Label> TestBehavior 绑定 OneWayToSource 不起作用。用于此的 XAML(来自原始问题)如下所示:

DataTemplate

<DataTemplate> <StackPanel> <Label Content="{Binding TestPropertyValue,ElementName=InnerTest}" Background="Cyan"> <b:Interaction.Behaviors> <tb:TestBehavior x:Name="InnerTest" TestPropertyValue="{Binding ItemTestViewModelValue,Mode=OneWayToSource}" /> </b:Interaction.Behaviors> </Label> <Label Content="{Binding ItemTestViewModelValue,Mode=OneWay}" Background="Lime" /> </StackPanel> </DataTemplate> 添加到 UpdateSourceTrigger=PropertyChanged 绑定会导致视图模型属性正确更新。更新后的 XAML 如下所示:

TestBehavior

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res