WPF-用户控件中的数据绑定? [英] WPF - Databinding in a UserControl?

查看:112
本文介绍了WPF-用户控件中的数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我还有一个关于数据绑定的问题.

简要项目说明:
我在Window1.xaml中有一个列表框,该列表框显示SQL数据库中的数据.更具体地说,数据库包含三个字段,名称",地址"和电话号码",并且列表框仅显示名称"字段.
我在UserControl1.xaml中有三个标签,我想在Window1 Lisbox中显示所选项目的名称",地址"和电话号码".

问题:
是否可以使用数据绑定从另一个窗口中的字段获取信息?

UserControl1.xaml代码:(当标签在同一窗口中时此代码有效,但当标签在UserControl中时该代码无效)

Hi Guys, I have another question this time regarding Databinding.

Brief Project Description:
I have a ListBox in Window1.xaml that is displaying data from a SQL Database. More specifically, the Database contains three fields, "Name", "Address" and "Phone Number" and the ListBox is displaying only the "Name" field.
I have three Labels in UserControl1.xaml that i would like to display the "Name", "Address" and "Phone Number" of the selected item in the Window1 Lisbox.

Question:
Is it possible to use Databinding to get information from a field in another window?

UserControl1.xaml Code: (this code works when the label is in the same window but not when the Label is in the UserControl)

<Label x:Name="nameLabel"

       Content="{Binding ElementName=listbox, Path=SelectedItem.Name}"/>


Window1.xaml代码:


Window1.xaml Code:

<Window.Resource>
    <DataTemplate x:Key="listboxTemplate">
        <TextBlock Text="{Binding Path=Name}"/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListBox x:Name="listbox" ItemTemplate="{StaticResource listboxTemplate}"/>
</Grid>

var query = from s in dc.People
            orderby s.Name
            select s;
listbox.ItemsSource = query.ToList();


预先感谢您的帮助,
Alex


Thanks in advance for your help,
Alex

推荐答案

答案:从Label ContentBinding中删除ElementName = listbox,然后在窗口中,当您添加UserControl1时,您可以简单地添加以下代码:
Answer: Remove the ElementName=listbox from the Label ContentBinding, then in the window, when you add the UserControl1 you simple add the following code:


这篇关于WPF-用户控件中的数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆