gpt4 book ai didi

wpf - 从 XAML 绑定(bind)到自定义依赖属性

转载 作者:行者123 更新时间:2023-12-02 00:28:15 27 4
gpt4 key购买 nike

我已经实现了一个自定义 DependencyProperty 并希望从 XAML 绑定(bind)到它。出于某种原因,它不会在更新绑定(bind)源 (MainWindow.Test) 时更新。绑定(bind)源不是 DP 但会触发 PropertyChanged 事件。然而,更新适用于非自定义依赖属性

作品:

<TextBlock Text="{Binding Test}" />

不起作用:

<local:DpTest Text="{Binding Test}"/>

有什么想法吗?


DP实现如下:

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

namespace WpfApplication3
{
public partial class DpTest : UserControl
{
public DpTest()
{
DataContext = this;
InitializeComponent();
}

public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(DpTest), new PropertyMetadata(string.Empty, textChangedCallBack));

static void textChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
int x = 5;
}
}
}

使用方法如下:

<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:local="clr-namespace:WpfApplication3" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Text="{Binding Test}"></TextBlock>
<local:DpTest Text="{Binding Test}"></local:DpTest>
<Button Click="Button_Click">Update</Button>
</StackPanel></Window>

带有绑定(bind)源的代码:

using System;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;

namespace WpfApplication3
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Test"));
}
}
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Test = "Updatet Text";
}
public event PropertyChangedEventHandler PropertyChanged;
}
}

最佳答案

不要UserControls 上设置 DataContext = this;,这样,如果您假设 DataContext,所有实例绑定(bind)都将失败 被继承,因为这会阻止它并且也很不可见。在 UserControl 绑定(bind)中,您应该命名控件并执行 ElementName 绑定(bind),或者使用 RelativeSource

例如

<UserControl Name="control" ...>
<TextBlock Text="{Binding Text, ElementName=control}"/>
<UserControl ...>
<TextBlock Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

关于wpf - 从 XAML 绑定(bind)到自定义依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7978011/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com