代码之家  ›  专栏  ›  技术社区  ›  Kamilos

WPF使用C#代码中的数据绑定用户控件

  •  1
  • Kamilos  · 技术社区  · 17 年前

    我创建了如下用户控件:

    public partial class View
        {
            public View()
            {
                InitializeComponent();
            }
    
            public static DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(TeaserView) );
    
            public string Name
            {
                get { return (string)GetValue(NameProperty); }
                set { SetValue(NameProperty, value); }
            }
    
        }
    

    XAML:

    <UserControl x:Class="Controls.View"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="200" Width="164">
        <Grid VerticalAlignment="Stretch"
              x:Name="Preview">
    
            <Label Height="28"  Content="{Binding ElementName=Preview, Path=Name}" Background="LightYellow" x:Name="name" VerticalAlignment="Top" ></Label>
        </Grid>
    </UserControl>
    

    并在Window1中简单地在XAML中使用它:

    <controls:View Height="200" Name="View1" Width="164" />
    

    我尝试在C#(本示例中的Name属性)中设置内容,但它不起作用,标签的内容仍然为空。(所有的推荐信等都很好)怎么了?

    5 回复  |  直到 17 年前
        1
  •  3
  •   Anvaka    17 年前

    我真的鼓励你从头到尾去读书。” DataBinding Overview “在MSDN上。它值得你花时间,相信我:)。事实上是完整的” Windows Presentation Foundation “这一部分值得您关注。

    对于您的代码,以下内容将起作用:

    <UserControl x:Class="WpfApplication5.View"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 Height="300"
                 Width="300"
                 DataContext="{Binding RelativeSource={RelativeSource Self}}">
      <Grid>
        <Label Height="28"
               Content="{Binding Path=Name}"
               Background="LightYellow"
               VerticalAlignment="Top"/>
      </Grid>
    </UserControl>
    

    但您确定要对家长隐藏“Name”属性吗?

        2
  •  1
  •   Guy Starbuck    17 年前

    您在用户控件上设置了datacontext吗?尝试将其设置为指向自己的代码隐藏:

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    
        3
  •  0
  •   Kamilos    17 年前

    我把Name属性作为示例。我正在尝试在Window1.xaml.cs中设置标签内容,如下所示:

    View1.Name = "Casablanca";
    
        4
  •  0
  •   Ugur Turan    17 年前

    尝试以下绑定,它应该可以工作:

    <Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:View}}, Path=Name}" />
    

    您还应该在文件顶部定义一个xmlns:local=“无论您拥有什么路径”。

    我还建议将“Name”DP重命名为其他名称,以避免名称串通。

        5
  •  0
  •   Tim Cooper    15 年前

    复制了您的精确代码,它工作正常。

    然而,它并没有做你可能期望它做的事情。您正在将绑定的源设置为 Grid 例子因此, Name UserControl 名称 财产 用户控制