【问题标题】:Databinding WPF数据绑定 WPF
【发布时间】:2010-03-02 18:09:51
【问题描述】:

我想创建一个带有 TextBox 的控件,并将 TextBox.Text 属性与我自己的依赖属性 TextProp 绑定。 (某种实验)但是,绑定不起作用!我做错了什么?

XAML:

    <UserControl x:Class="WpfApplication1.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:WpfApplication1">
            <TextBox Text="{Binding TextProp}" x:Name="textb"/>
    </UserControl>

C#:

public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
            TextProp = "fwef";
        }

        public string TextProp
        {
            get { return ( string )GetValue(TextPropProperty); }
            set { SetValue(TextPropProperty, value); }
        }

        public static readonly DependencyProperty TextPropProperty =
            DependencyProperty.Register("TextProp",typeof( string ),typeof(UserControl1));
    }

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    您好像忘记设置DataContext,Binding 可以从中获取实际属性...

    尝试以下方法之一:

    C#

    public UserControl1()
    {
       InitializeComponent();
       TextProp = "fwef";
       DataContext = this;
    }
    

    或者

    <UserControl x:Class="WpfApplication1.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:WpfApplication1"
                 DataContext="{Binding RelativeSource={RelativeSource Self}}">
                <TextBox Text="{Binding TextProp}" x:Name="textb"/>
        </UserControl>
    

    或 2

    <UserControl x:Class="WpfApplication1.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:WpfApplication1">
            <TextBox DataContext="{Binding RelativeSource={RelativeSource FindAncestory, AncestorType={x:Type local:UserControl}}} Text="{Binding TextProp}" x:Name="textb"/>
    </UserControl>
    

    这是我从头开始写的,希望我没有在这里打错字。

    希望对你有帮助,

    干杯。

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 2010-10-30
      • 2015-05-24
      • 2015-06-23
      • 2012-12-28
      • 2015-11-23
      • 2011-01-01
      • 2010-11-04
      相关资源
      最近更新 更多