繁体   English   中英

WPF绑定项目控件子控件

[英]WPF Binding itemscontrol child controls

我有一个跨多个页面使用的用户控件,该控件定义了标题标签和两个按钮。 我希望控件能够具有子控件,但是由于这些子控件位于项集合中,因此我遇到了绑定这些子控件的问题。 当我向XAML中的子控件添加绑定时,它们没有被注册。

错误输出: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MyPage'. BindingExpression:Path=MyText; DataItem=null; target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MyPage'. BindingExpression:Path=MyText; DataItem=null; target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

为简洁起见,省略了多余的代码。

例如

XAML

<UserControl x:Class="MyControl" Name="MyControl">
    <Grid>
        <ItemsControl Name="ItemsControl" ItemsSource="{Binding ItemsSource, ElementName=MyControl}" />
    </Grid>
</UserControl>

背后的代码

[ContentProperty("Items")]
public partial class MyControl : UserControl
{
    public static readonly DependencyProperty ItemsSourceProperty =
            ItemsControl.ItemsSourceProperty.AddOwner(typeof (MyControl));

    public IEnumerable ItemsSource
    {
        get { return (IEnumerable) GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public ItemCollection Items
    {
        get { return ItemsControl.Items; }
    }
}

用法:

<Page x:Class="MyPage" Name="MyPage">
    <MyControl>
        <TextBox Text="{Binding MyText,
                        ElementName=MyPage,
                        UpdateSourceTrigger=PropertyChanged}" />
    </MyControl>
</Page>

背后的代码

public partial class MyPage : Page, INotifyPropertyChanged
{
    private string _myText;
    public string MyText
    {
        get{ return _myText; }
        set
        {
            _myText = value;
            OnPropertyChanged("MyText");
        }
    }
}

我希望能够将TextBox数据绑定到MyText属性,以便每当我在其后面的代码中对其进行修改时,都将在页面上对其进行更新。

将我的评论转换为答案:

删除ElementName并尝试RelativeSource={RelativeSource FindAncestor, AncestorType=Page}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM