微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WPF 绑定到用户控件失败

如何解决WPF 绑定到用户控件失败

在这里找不到类似的问题。如果我复制了主题,请纠正我。

我创建了一个用户控件:

    <UserControl x:Class="ToolBox.ctrl.LabeledTextBox"
             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:ToolBox.ctrl"
             mc:Ignorable="d" 
             >
    <StackPanel>
        <Label Content="{Binding Label}" FontSize="10" Height="25" Foreground="{StaticResource MainFontColor}" VerticalContentAlignment="Bottom"/>
        <TextBox Text="{Binding Body}" Height="25" FontSize="12"/>
    </StackPanel>
</UserControl>

类:

public partial class LabeledTextBox : UserControl
{
    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label",typeof(String),typeof(LabeledTextBox));
    public static readonly DependencyProperty BodyProperty = DependencyProperty.Register("Body",typeof(LabeledTextBox));

    public string Label
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty,value); }
    }

    public string Body
    {
        get { return (string)GetValue(BodyProperty); }
        set { SetValue(BodyProperty,value); }
    }

    public LabeledTextBox()
    {
        InitializeComponent();
        this.DataContext = this;
    }
}

我在 MainWindow.xaml 中使用它:

<Grid x:Name="SomeGrid">
        <Grid.ColumnDeFinitions>
            <ColumnDeFinition Width="1*"/>
            <ColumnDeFinition Width="2*"/>
            <ColumnDeFinition Width="1*"/>
        </Grid.ColumnDeFinitions>
        <ctrl:LabeledTextBox Grid.Column="0" Label="Site ID:" Body="{Binding SiteID}" />
        <ctrl:LabeledTextBox Grid.Column="1" Label="Site Name:" Body="{Binding SiteName}" Margin="5,0"/>
        <ctrl:LabeledTextBox Grid.Column="2" Label="Channel of Trade:" Body="{Binding TradeChannel}" Margin="5,0"/>
     </Grid>

我有一个对象列表,我想将“SomeGrid”的 DataContext 设置为该列表中的第一个对象

SomeGrid.DataContex = list.First();

如果我在这个网格中放置一个 TextBox 控件,那么它工作得非常好,然后绑定正在工作,由于某种原因,用户控件绑定将无法工作。我做错了吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。