加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WPF绑定到变量/ DependencyProperty

发布时间:2020-12-15 18:21:28 所属栏目:百科 来源:网络整理
导读:我正在玩 WPF Binding和变量.显然,只能绑定DependencyProperties.我想出了以下内容,效果非常好: 代码隐藏文件: public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); } public string Test { get { return (string)th
我正在玩 WPF Binding和变量.显然,只能绑定DependencyProperties.我想出了以下内容,效果非常好:
代码隐藏文件:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public string Test
    {
        get { return (string)this.GetValue(TestProperty); }
        set { this.SetValue(TestProperty,value); }
        //set { this.SetValue(TestProperty,"BBB"); }
    }
    public static readonly DependencyProperty TestProperty = DependencyProperty.Register(
      "Test",typeof(string),typeof(MainWindow),new PropertyMetadata("CCC"));

    private void button1_Click(object sender,RoutedEventArgs e)
    {
        MessageBox.Show(Test);
        Test = "AAA";
        MessageBox.Show(Test);
    }
}

XAML:

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <TextBox Height="31" HorizontalAlignment="Left" Margin="84,86,0" Name="textBox1" VerticalAlignment="Top" Width="152" 
             Text="{Binding Test,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}"/>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="320,85,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <TextBox Height="31" HorizontalAlignment="Left" Margin="84,138,0" Name="textBox2" Text="{Binding Test,Mode=TwoWay}" VerticalAlignment="Top" Width="152" />
</Grid>

两个TextBoxes另一个更新.按钮将它们设置为“AAA”.

但是现在我将Setter函数替换为注释掉的函数(模拟给定值的某些操作).我希望每当属性值改变时,它将被重置为“BBB”.当您按下按钮时,即在代码中设置属性时,它会这样做.但它确实不会影响WPF Bindings,也就是说你可以改变TextBox内容,从而改变属性,但显然从未调用过Setter.
我想知道为什么会这样,以及如何实现预期的行为.

解决方法

永远不会保证调用依赖属性的CLR属性包装器,因此,您不应该在那里放置任何其他逻辑.无论何时在更改DP时需要其他逻辑,都应使用属性更改的回调.

在你的情况下..

public string Test
{
    get { return (string)this.GetValue(TestProperty); }
    set { this.SetValue(TestProperty,value); }
}

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register("Test",new PropertyMetadata("CCC",TestPropertyChanged));

private static void TestPropertyChanged(DependencyObject source,DependencyPropertyChangedEventArgs e)
{
    MainWindow mainWindow = source as MainWindow;
    string newValue = e.NewValue as string;
    // Do additional logic
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读