如何在wpf中的用户控件中使用命令绑定?

2024-02-26

在主窗口中,命令绑定工作正常。 在 UserControl 1 中它不起作用。请注意,数据上下文设置正确,作为绑定结果的按钮内容证明了这一点。

我并不是试图将用户控件中的命令绑定到主窗口中的命令或任何其他此类技巧。我只是想复制我在 UserControl1 的 MainWindow 中所做的事情。

主窗口 XAML

<StackPanel>
    <Button Content="Click Here" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
    <local:UserControl1></local:UserControl1>
</StackPanel>

主窗口代码隐藏

public partial class MainWindow : Window
{
    public static RoutedCommand ClickHereCommand { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        ClickHereCommand = new RoutedCommand();
        CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
    }

    public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        System.Windows.MessageBox.Show("hello");
    }
}

用户控制 XAML

<UserControl x:Class="CommandBindingTest.UserControl1"
         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" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" x:Name="root">

<Grid DataContext="{Binding ElementName=root}" >
    <Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>
</UserControl>

用户控制代码隐藏

public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    private string _ButtonContent;
    public string ButtonContent
    {
        get { return _ButtonContent; }
        set
        {
            if (_ButtonContent != value)
            {
                _ButtonContent = value;
                OnPropertyChanged("ButtonContent");
            }
        }
    }

    public static RoutedCommand ClickHereCommand { get; set; }


    public UserControl1()
    {
        InitializeComponent();
        ClickHereCommand = new RoutedCommand();
        CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
        ButtonContent = "Click Here";
    }

    public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        System.Windows.MessageBox.Show("hello from UserControl1");
    }


    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

这是最好的解决方案:

 <Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" >
        <Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
 </Grid>

其他解决方案:

你忘记设置了数据上下文 to 用户控制1.

  public UserControl1()
        {
            InitializeComponent();
            ClickHereCommand = new RoutedCommand();
            CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
            ButtonContent = "Click Here";
            this.DataContext = this;
        }

之后你必须删除用户控制1网格中的数据上下文。

This:

<Grid DataContext="{Binding ElementName=root}" >
    <Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>

你必须更改为:

<Grid>
        <Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>

UserControl 中未设置 DataContext 的解决方案:

您必须将 ButtonContent 和 ClickHereCommand 更改为 DependencyProperty。

        public string ButtonContent
        {
            get { return (string)GetValue(ButtonContentProperty); }
            set { SetValue(ButtonContentProperty, value); }
        }

        public static readonly DependencyProperty ButtonContentProperty =
            DependencyProperty.Register("ButtonContent", typeof(string), typeof(UserControl1), new UIPropertyMetadata(string.Empty));

        public RoutedCommand ClickHereCommand
        {
            get { return (RoutedCommand)GetValue(ClickHereCommandProperty); }
            set { SetValue(ClickHereCommandProperty, value); }
        }

        public static readonly DependencyProperty ClickHereCommandProperty =
            DependencyProperty.Register("ClickHereCommand", typeof(RoutedCommand), typeof(UserControl1), new UIPropertyMetadata(null));

并在演员UserControl1:

 public UserControl1()
    {
        InitializeComponent();

        ClickHereCommand = new RoutedCommand();
        CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));            
        ButtonContent = "Click Here";
        //this.DataContext = this;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在wpf中的用户控件中使用命令绑定? 的相关文章

  • OpenGL,如何独立旋转对象?

    到目前为止我的代码 void display void glClear GL COLOR BUFFER BIT GL DEPTH BUFFER BIT Clear Screen And Depth Buffer glLoadIdentity
  • 以概率从列表中选择随机元素

    我有一个包含四个项目 A B C D 的列表 每个项目都有被选择的概率 例如 A 有 74 的机会被选中 B 15 C 7 D 4 我想创建一个函数 根据其概率随机选择一个项目 有什么帮助吗 为您的项目定义一个类 如下所示 class It
  • lambda 表达式到函数指针的转换

    这是这个问题的后续问题 Lambda 如何作为参数传递 https stackoverflow com questions 3321283 c0x lambda how can i pass as a parameter 据推测 MSDN
  • 用C#发送USSD?

    我想编写一个在 Windows Mobile 6 上运行的简单 C 应用程序 它可以发送 USSD 消息 有没有任何图书馆可以帮助我做到这一点 或者是否有任何示例解释如何使用线路发送USSD http msdn microsoft com
  • 公共领域有哪些替代方案?

    我正在用 java 编写一个游戏 正如问题标题建议的那样 我在类中使用公共字段 暂且 据我所知 公共领域很糟糕 我有一些理解其中的原因 但如果有人能澄清为什么你不应该使用它们 那将不胜感激 问题是 从我所看到的来看 这似乎是合乎逻辑的 是使
  • 有没有办法关闭 Hangfire 使用 Serilog 进行的日志记录?

    有没有办法关闭 Hangfire 使用 Serilog 进行的日志记录 我们正在使用我们自己的抽象 我不希望在使用 Serilog 时来自 Hangfire 记录器的所有额外噪音 INIT call under web project na
  • WCF 客户端返回空数组 - XML 响应似乎正常

    我正在尝试为我们的 Intranet 上托管的 Web 服务创建一个简单的 WCF 客户端 C 使用 Fiddler 和 SoapUI 我可以看到请求和响应似乎正常 但是当我运行代码时返回一个空数组 我会尝试只粘贴相关的行 但会是很多东西
  • 调试WCF时无法自动单步进入服务器

    我得到了可怕的 无法自动进入服务器 无法调试远程过程 这通常表明服务器上尚未启用调试 现在 我一直在读我需要添加
  • 泛型类上的 DebuggerDisplay

    我在应用时遇到问题DebuggerDisplay泛型类的属性 DebuggerDisplay foo class Foo DebuggerDisplay Bar t class Bar
  • C++ 为非虚方法指定初始化

    我有 a h 如下所示 class A public void doSomething 0 然后我有 b h 如下所示 include a h class b public A public void doSomething 我只是想通过尝
  • C++头文件问题

    我在处理类时尝试了一些 C 代码 这个问题出现在我身上 并且让我有点烦恼 我创建了一个包含类定义的头文件和一个包含实现的 cpp 文件 如果我在不同的 cpp 文件中使用此类 为什么要包含头文件而不是包含类实现的 cpp 文件 如果我包含类
  • 我的 Opencv 应用程序处理速度非常慢

    我正在构建一个 OpenCV 应用程序 它从相机捕获视频 并在删除背景后将其覆盖在另一个视频上 我无法达到合理的速度 因为它以大约 1 fps 的速度播放输出 而我的背景去除以 3 fps 的速度工作 有没有办法以正常速度显示背景视频并以
  • C# 的 xml 序列化中是否有一个属性可以跳过空数组?

    C 的 xml 序列化中是否有一个属性可以跳过空数组 这将提高 xml 输出的可读性 好吧 你也许可以添加一个ShouldSerializeFoo method using System using System ComponentMode
  • 将纬度/经度转换为 X/Y,以便在美国地图图像上进行阿尔伯斯投影

    我正在尝试使用 C 或 Javascript 将纬度 经度转换为 X Y 坐标 以将带有 CSS 的 div 左 上 定位到美国地图的背景图像上 美国的标准地图投影是阿尔伯斯投影 如下所示 但 StackOverflow 仅提供参考基本墨卡
  • Lambda 按值捕获和“mutable”关键字

    关键词的必要性mutable在 lambda 中 是造成极大混乱的根源 考虑代码 int x 10 function
  • int 类型的构造函数

    考虑到成本 这些情况是否相同 case 1 int a 5 case 2 int a 5 case 3 int a a 5 这三种语法是不同的 请耐心等待 我使用用户定义类型而不是 int 稍后我将回到 int T a 5 Direct i
  • 恐怖分子已弃用

    正在接听另一个问题 https stackoverflow com q 11830514 1468366 我偶然发现了man page http linux die net man 3 herror一个名为的函数herror 看起来很像pe
  • 致命:所有操作都需要OperationId。请为路径的“获取”操作添加它

    我正在使用 AutoRest 从 swagger json 生成 api 的客户端 输出是 AutoRest code generation utility cli version 3 0 6187 node v10 16 3 max me
  • 返回右值 - 这段代码有什么问题? [复制]

    这个问题在这里已经有答案了 我遇到了以下代码片段 std string test std string m Hello return std move m int main std string m test 我知道上面的代码是不正确且不安
  • 我应该为每个 Web 请求使用静态缓存的 ResourceManager 还是一个新实例?有关系吗?

    创建新的 NET 对性能 或其他 有何影响 如果有 ResourceManager根据每个请求new ResourceManger myResourceType FullName myResourceType Assembly 与在 Des

随机推荐

  • Slug 大小对于 Heroku 上的 Flask 应用程序来说太大

    我正在部署一个非常简单的烧瓶应用程序 带有面部识别模型 我只是将 Flask 应用程序代码和模型权重推送到 Heroku 我的 slug 大小仍然是 556M 超过了 500M 的限制 我在requirements txt 中有最低要求 这
  • 为什么从返回 int32_t 的函数返回 0x80000000 不会导致警告?

    考虑 int32 t f return 0x80000000 为什么这不会导致编译器警告 至少在 GCC 上 0x80000000 超出范围int32 t INT32 MAX is 0x7fffffff 我相信这应该会导致隐式转换 这是正确
  • 在 AWS Lambda 函数中使用 Django ORM

    我有一个现有的 Django 应用程序数据存储在 Postgres RDS 下 现在我想通过 lambda AWS 函数和 Django 风格的 ORM 查询 更新数据 我知道理论上这是可能的 如果 使用 lambda 函数打包整个 Dja
  • 如何进行水平视差滚动

    我正在使用最新版本的 Bootstrap JQuery 和 Skrollr 我想要一个静态背景和几个在您通过视差滚动滚动时出现的场景 我可以在您滚动时制作场景 但我正在寻找一种方法 让您看起来不会向下移动页面 我正在寻找像这样的图像的场景
  • 使用 BigQuery 查询地理空间数据

    您好 我想获取基于 GPS 坐标的公共场所 餐厅 酒店 电影院等 邻居列表 BigQuery 可以做到这一点吗 如果您将经纬度或 GPS 坐标作为列 那么您绝对可以使用坐标上的 WHERE 比较从 BigQuery 中获取矩形区域 然后在选
  • 在 Windows 10 中找不到 tools.jar React Native Android

    伙计们 我只是尝试在我的笔记本电脑上安装 React Native 我已遵循所有设置说明 但仍然收到这些错误 What went wrong Execution failed for task app compileDebugJavaWit
  • 使用训练有素的 Spark ML 模型提供实时预测[重复]

    这个问题在这里已经有答案了 我们目前正在测试一个基于 Spark 在 Python 中实现 LDA 的预测引擎 https spark apache org docs 2 2 0 ml clustering html latent diri
  • 如何使用堆在线性时间内找到数字的中位数?

    维基百科 http en wikipedia org wiki Heap data structure Heap applications says 选择算法 找到最小值 最大值 最小值和最大值 median 或者 甚至第 k 大元素也可以
  • 在Windows中设置子进程名称?

    我有一个进程 它运行多次子进程 每个子进程都没有 GUI 并且需要为任务管理器的所有子进程设置不同的 名称 和 描述 可以使用Win API吗 我找不到 Windows 系列的解决方案 我查看了 WriteProcessMemory 但它看
  • 使用 JavaScript 的 Selenium Webdriver,如何使用 chrome.exe 的特定路径启动 Chrome?

    我有以下 Javascript 代码 它使用由指定的 Chrome 路径启动 ChromePATH环境变量 let driver await new Builder forBrowser chrome build 如何使用 Chrome 的
  • 在 Python 中打开 URL 并获取最多 X 字节的最佳方法是什么?

    我想让机器人每小时获取一个 URL 但如果网站运营商是恶意的 他可以让他的服务器向我发送一个 1 GB 的文件 有没有好的方法可以将下载限制为 100 KB 并在该限制之后停止 我可以想象从头开始编写自己的连接处理程序 但如果可能的话 我想
  • 设置从磁盘加载的背景图像

    我想在运行时更改 QFrame 背景 但是 我会从磁盘 图像 加载背景 在 QFrame 中设置样式表不起作用 因为图像不在资源中 一种方法是设置 QPushButton 图标 例如 QPixmap img images 01 png ui
  • JMeter:为单个用户触发多个并发 HTTP 请求

    我有一个带有线程组和 Cookie 管理器的 JMeter 负载测试脚本 线程组中的用户首先使用HTTP采样器登录来获取cookie 然后 循环控制器触发交错采样器 该采样器在几个向服务器发出查询的 HTTP 采样器之间交替 现在 我希望交
  • Delphi:更好的设计以避免循环单元引用?

    我在 Delphi 10 中有一个三角形网格结构 出于性能原因 我将网格顶点 三角形面等的数据存储在 TList 的后代中 我让 TList 为列表中的每个成员进行计算 对于这些计算 我需要访问 TMesh 结构的某些字段 因此 在创建 T
  • SVG - 从窗口坐标到ViewBox坐标

    基本上我有一个 svg SecondSVG 到一个 svg FirstSVG 到一个 svg MainSVG 每个 svg 都有自己的 ViewBox 该页面可以由另一个页面加载到屏幕上的任何位置 那么基本上我如何找到 SecondSVG
  • 单击时填充 HTML 下拉列表

    我有一个包含多个 HTML 的页面select下拉菜单 并且需要人口onclick的元素 此填充是通过在单击事件侦听器中使用 AJAX 调用完成的select元素 原因是性能和负载非常关键 因此不能在页面加载时填充它们 另外 设计must使
  • 在默认构造函数或内联初始化变量之间有区别吗? [复制]

    这个问题在这里已经有答案了 我在 Java 中发现了一些相关问题 但没有找到与 C 相关的问题 因此请原谅任何重复的问题 又短又甜 有什么区别 有没有 public static class Foo public static List
  • 与 if 语句中的字符串进行比较不起作用

    我尝试比较从 scanf 和 fscanf 获得的两个字符串 我已经弄清楚每个变量里面的内容是什么 它都显示相同的字符串 但是当我在 if 语句中与这两个字符串进行比较后 它不起作用并执行 else 语句 我的代码有什么问题吗 int ma
  • 如何使 jetty-maven-plugin 部署从存储库检索的战争?

    我正在为一个大型网络项目设置一个集成测试模块 集成测试模块与Web项目本身分离 并且有自己的pom xml 这个想法是使用 maven soapui plugin 发送请求并验证响应 设置soapui插件并不麻烦 但是 我无法弄清楚如何告诉
  • 如何在wpf中的用户控件中使用命令绑定?

    在主窗口中 命令绑定工作正常 在 UserControl 1 中它不起作用 请注意 数据上下文设置正确 作为绑定结果的按钮内容证明了这一点 我并不是试图将用户控件中的命令绑定到主窗口中的命令或任何其他此类技巧 我只是想复制我在 UserCo