将 wpf 用户控件绑定到父属性

2024-02-02

我有一个简单的用户控件,其中包含一个图像,我想根据父级(可能是另一个 UC 或窗口)中的属性更改其源。 UC 的简化版本如下所示

<UserControl x:Class="Test.Controls.DualStateButton" ... x:Name="root">
    <Grid>
        <Image Height="{Binding Height, ElementName=root}" Stretch="Fill" Width="{Binding Width, ElementName=root}">
            <Image.Style>
                <Style TargetType="{x:Type Image}">
                    <Setter Property="Source" Value="{Binding ImageOff, ElementName=root}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding State}" Value="True">
                            <Setter Property="Source" Value="{Binding ImageOn, ElementName=root}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
    </Grid>
</UserControl>

Height、Width、ImageOff、ImageOn 和 State 都是 UC 的依赖属性。 UC 没有设置 DataContext,因此它应该继承父级。我想要做的是如下所示,其中 UC 中的 State 绑定到 Window 的 DualState 属性。

<Window x:Class="Test.MainWindow" DataContext="{Binding RelativeSource={RelativeSource Self}}">
...
    <Grid>
        <local:DualStateButton State="{Binding DualState}" Height="100" ImageOff="{StaticResource ButtonUp}" ImageOn="{StaticResource ButtonDown}" Width="100"/>
    </Grid>
</Window>

然而,我得到的是一个错误,指出在“对象”“MainWindow”上找不到“State”属性,因此它似乎是按字面意思获取 UC 中的绑定“State”,而不是将其分配给的 DualState 属性窗户。有人可以洞察我做错了什么吗?

如果我通过代码或 XAML(作为布尔值)设置 UC 上的 State 属性,它就可以正常工作。状态 DP 定义如下。

public static readonly DependencyProperty StateProperty =
    DependencyProperty.Register("State", typeof(bool), typeof(DualStateButton),
    new PropertyMetadata(false));

public bool State
{
    get { return (bool)GetValue(StateProperty); }
    set { SetValue(StateProperty, value); }
}

它的数据类型是否需要是绑定或其他东西才能正常工作?


DataTrigger 的 DataContext 设置为窗口,这就是它在窗口中查找“状态”的原因。您只需告诉绑定状态位于用户控件上。尝试这个:

<DataTrigger Binding="{Binding Path=State, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" Value="True">

这是一个完整的例子:

主窗口.xaml

<Window x:Class="WpfApplication89.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        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:local="clr-namespace:WpfApplication89"
        mc:Ignorable="d"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <local:UserControl1 State="{Binding Path=DualState}" />
        <CheckBox Content="DualState" IsChecked="{Binding DualState}" />
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System.Windows;

namespace WpfApplication89
{
    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty DualStateProperty = DependencyProperty.Register("DualState", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        public bool DualState
        {
            get { return (bool)GetValue(DualStateProperty); }
            set { SetValue(DualStateProperty, value); }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

用户控件1.xaml

<UserControl x:Class="WpfApplication89.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" 
             xmlns:local="clr-namespace:WpfApplication89"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="User Control 1">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Setter Property="Background" Value="Beige" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=State, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" Value="true">
                            <Setter Property="Background" Value="Red" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    </Grid>
</UserControl>

用户控件1.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication89
{
    public partial class UserControl1 : UserControl
    {
        public static readonly DependencyProperty StateProperty = DependencyProperty.Register("State", typeof(bool), typeof(UserControl1), new PropertyMetadata(false));

        public bool State
        {
            get { return (bool)GetValue(StateProperty); }
            set { SetValue(StateProperty, value); }
        }

        public UserControl1()
        {
            InitializeComponent();
        }
    }
}

MainWindow.xaml.cs(INotifyPropertyChanged 版本)

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace WpfApplication89
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName]string name = null)
        {
            if (Equals(field, value))
            {
                return false;
            }
            field = value;
            this.OnPropertyChanged(name);
            return true;
        }
        protected void OnPropertyChanged([CallerMemberName]string name = null)
        {
            var handler = this.PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        #endregion

        #region Property bool DualState
        private bool _DualState;
        public bool DualState { get { return _DualState; } set { SetProperty(ref _DualState, value); } }
        #endregion


        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 wpf 用户控件绑定到父属性 的相关文章

随机推荐

  • 如何检查Documents文件夹中是否存在文件?

    我有一个应用程序内购买的应用程序 当用户购买东西时 将一个 html 文件下载到我的应用程序的 Documents 文件夹中 现在我必须检查此 HTML 文件是否存在 如果存在 则加载此 HTML 文件 否则加载我的默认 html 页面 我
  • Java 日志记录级别混乱

    我将日志记录级别设置为 CONFIG 但没有看到 CONFIG 级别上写入的消息 我缺少什么 配置 Logger logger java util logging Logger getLogger xxx logger setLevel j
  • 带有 Google Cloud Messaging 的 Google App Engine 后端

    我正在使用下面页面上的示例代码尝试基于 GAE 的后端 https github com GoogleCloudPlatform gradle appengine templates tree master GcmEndpoints htt
  • Gatsby:基于 window.innerWidth 行为不当做出反应条件渲染

    组件的条件渲染基于window innerWidth似乎没有按预期工作生产建立基于盖茨比的网站 我用来检查视口宽度的钩子 以及对窗口全局的额外检查以避免 Gatsby node 生产构建错误 如下所示 import useState use
  • IIS 7.0 - IIS 在缓存控制中添加“私有”,它来自哪里

    因为我们保护 PDF 文件免受匿名用户的侵害 所以我们有一个自定义处理程序 因此我们有一个条目 我们还对 http 标头进行了更改 通过 IIS 7 管理添加 cache control no cache no store 该管理在 sys
  • gson 格式错误的 json 异常

    我是 gson 将我的字符串转换为 jsonObject 下面是代码片段 String s orig 2334 342 Gson gson new Gson SamplePojo jsn gson fromJson s SamplePojo
  • 数据库记录锁定

    我有一个服务器应用程序和一个数据库 服务器的多个实例可以同时运行 但所有数据都来自同一个数据库 在某些服务器上是 postgresql 在其他情况下是 ms sql server 在我的应用程序中 执行一个过程可能需要几个小时 我需要确保该
  • 如果文件不存在于给定的本地文件列表中,则从 FTP 下载文件

    我有一个 FTP 服务器 我想从中下载本地目录中不存在的所有文件 我尝试做一个For Next但我就是无法理解它 我尝试枚举这些文件 但由于对两个列表都执行了该操作 所以出现错误 我认为该错误可能是由于交叉检查在线文件与本地列表中的单个枚举
  • 如何在 SQL 脚本中使用新值更新 XML 元素

    我在其中一列中有 XMLXYZ表 我需要更新Amount具有新值而不是 0 00 的元素 并且PolicyReference and AccountReference具有两个不同值而不是空白的元素 例如
  • EditText 具有单个文本行、换行和完成操作吗?

    我想有一个EditText使用软键编辑时具有以下特征 我准备好了文档 在这里搜索 使用参数 但找不到工作配置 The EditView屏幕上的视图具有几行的高度 例如 3 4 内容文本是单行 即没有换行符 如果内容文本比视图的宽度长 它应该
  • Ruby on Rails - 引用同一模型两次?

    是否可以建立双重关系activerecord模型通过generate scaffold命令 例如 如果我有一个User模型和一个PrivateMessage模型中 private messages 表需要跟踪sender and recip
  • 将数据导入 Matlab

    我有一个 csv 文件 其中包含我想要导入到 Matlab 中的数据 因为它是日期和数字的混合 所以我使用 data textscan fid s s n n n n n 819500 headerlines 1 delimiter 不幸的
  • 交换字符串中出现频率最高的两个字母

    我不知道我的代码有什么问题 但是当我编译时我得到 warning passing arg 2 of strcspn makes pointer from integer without a cast 这是代码 include
  • 在 Java 中读取 CSV 文件时跳过第一行

    我正在编写一个解析器代码来读取 csv 文件并将其解析为 XML 这是我拥有的代码并且它可以工作 但我希望它跳过文件中的第一行 所以我决定设置一个HashMap 但它似乎不起作用 for int i 0 i lt listOfFiles l
  • heightForRowAtIndexPath iOS 中的 EXC_BAD_ACCESS

    我正在开发一个应用程序 其中有 UITableViewCell 的自定义子类 我想根据单元格内部的文本使单元格的高度动态化 我尝试在 heightForRowAtIndexPath 方法中执行此操作 但我遇到了一些问题 以下代码导致 EXC
  • 设置 Facebook SDK 进行后处理会导致控制台中出现错误消息

    我对此没有明显的影响 但我正处于项目的最后阶段 并且正在努力注意任何警告 每次在 Xcode 控制台中启动时 将以下行添加到 App Delegate 下时 我都会收到来自 FB 的 3 条警告日志application didFinish
  • EntityType“DbGeography”没有定义键

    长期听众 第一次来电 终于在这里注册了帐户 我在用视觉工作室2013 with NET 4 5 1 and 实体框架6 最终版本 不是 RC 或测试版 当尝试将 DbGeography 属性添加到我的实体时 我在执行时收到此错误 One o
  • 如何让 *ant* 不打印 javac 警告?

    我现在只想打印出错误 而不是其他任何内容 谢谢 你有没有尝试过
  • 如何在首次加载时获取 htaccess 文件设置的 cookie

    我需要在第一次加载页面时获取 cookie 值 我知道可以在第二次加载时检索 cookie 我需要这个 因为我想根据服务器 htaccess 文件设置的 cookie 值进行重定向 我在 htaccess 文件中以这种方式设置 cookie
  • 将 wpf 用户控件绑定到父属性

    我有一个简单的用户控件 其中包含一个图像 我想根据父级 可能是另一个 UC 或窗口 中的属性更改其源 UC 的简化版本如下所示