wpf 如何使用 DependencyProperty 设置 TextBox 的绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26161900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:35:17  来源:igfitidea点击:

How to set Binding of TextBox with DependencyProperty

c#wpfxamldata-bindingtextbox

提问by user3692104

I have a custom UserControl with a DataGrid and a TextBox, I am trying to databind things to these elements using DependencyProperties. The binding works fine for the DataGrid but not for the TextBox.

我有一个带有 DataGrid 和 TextBox 的自定义 UserControl,我正在尝试使用 DependencyProperties 将事物数据绑定到这些元素。该绑定适用于 DataGrid,但不适用于 TextBox。

Code:

代码:

public static readonly DependencyProperty BuiDataProperty = DependencyProperty.Register("BuiData", typeof(IEnumerable), typeof(BelastingTab), new PropertyMetadata(default(IEnumerable), BuiDataChanged));

private static void BuiDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var Object = d as BelastingTab;
    if (Object == null) return;
    Object.BuiDataDataSourceChanged(d, e);
}

private void BuiDataDataSourceChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
    BuiDataTabel.ItemsSource = dependencyPropertyChangedEventArgs.NewValue as IEnumerable;
}

public IEnumerable BuiData
{
    get { return (IEnumerable)GetValue(BuiDataProperty); }
    set { SetValue(BuiDataProperty, value); }
}

And in the main XAML:

在主 XAML 中:

<src:BelastingTab BuiData="{Binding Path=Static.BuienRegulier[0].BuiTabel}"/>

This is the code for setting the binding of the DataGrid, how would I go about doing the same for the TextBox?

这是用于设置 DataGrid 绑定的代码,我将如何为 TextBox 做同样的事情?

EDIT: This is what I have currently,

编辑:这就是我目前所拥有的,

Main XAML:

主要 XAML:

<src:BelastingTab BuiData="{Binding Path=Static.BuienRegulier[0].BuiTabel}" HerhalingsTijd="{Binding Path=Static.BuienRegulier[0].HerhalingsTijd}"/>

This refers to a string. In the UserControl XAML:

这是指一个字符串。在用户控件 XAML 中:

<TextBox Text="{Binding HerhalingsTijd, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

In the UserControl XAML CS:

在 UserControl XAML CS 中:

public static readonly DependencyProperty HerhalingsTijdProperty = DependencyProperty.Register("HerhalingsTijd", typeof(string), typeof(BelastingTab), new PropertyMetadata(string.Empty));

public string HerhalingsTijd
{
    get { return (string)GetValue(HerhalingsTijdProperty); }
    set { SetValue(HerhalingsTijdProperty, value); }
}

采纳答案by XMight

I see no problem in doing what you want. I created a simple test application. I will provide here the code, hope it will help you somehow to fix what you have wrong.

我认为做你想做的没有问题。我创建了一个简单的测试应用程序。我将在这里提供代码,希望它可以帮助您以某种方式修复您的错误。

The UserControl1 code:

UserControl1 代码:

public partial class UserControl1 : UserControl
{
    public static DependencyProperty TxtBoxValueProperty = DependencyProperty.Register("TxtBoxValue", typeof(String), typeof(UserControl1));

    public String TxtBoxValue
    {
        get { return (String)GetValue(TxtBoxValueProperty); }
        set 
        {
            SetValue(TxtBoxValueProperty, value);
        }
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == TxtBoxValueProperty)
        {
            // Do whatever you want with it
        }
    }

    public UserControl1()
    {
        InitializeComponent();
    }
}

User control Xaml:

用户控件 Xaml:

<StackPanel>
    <TextBox Text="{Binding TxtBoxValue, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=1}, Mode=TwoWay}" Width="100" Height="50"/>
    <TextBox></TextBox>
</StackPanel>

Main window xaml:

主窗口 xaml:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:WpfApplication1"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <local:UserControl1 TxtBoxValue="{Binding TextBoxValue, Mode=TwoWay}"></local:UserControl1>
</Grid>

Main window code behind:

后面的主窗口代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    CancellationTokenSource cTS;
    CancellationToken cT;

    private String _textBoxValue;
    public String TextBoxValue
    {
        get { return _textBoxValue; }
        set 
        {
            _textBoxValue = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("TextBoxValue"));
            }

            if (_textBoxValue.Contains("enough"))
            {
                cTS.Cancel();
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        cTS = new CancellationTokenSource();
        cT = cTS.Token;
        Task.Factory.StartNew(ChangeTextBoxValue, cT);
    }

    public void ChangeTextBoxValue()
    {
        while (true)
        {
            Random rnd = new Random(DateTime.Now.Millisecond);
            TextBoxValue = (rnd.NextDouble() * 1000.0).ToString();
            Thread.Sleep(10000);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Note that I have written this very fast and did how I usually use it (except notify that I put in a ViewModelBase).

请注意,我写得非常快,并且按照我通常的使用方式进行了编写(除了通知我放入了 ViewModelBase)。

If this doesn't work in your case, it is either I did not understand the question, or you have something very specific, but I doubt that.

如果这在你的情况下不起作用,要么是我没有理解这个问题,要么你有一些非常具体的东西,但我对此表示怀疑。