在另一个窗口中访问UserControl控件

时间:2011-12-02 18:48:15

标签: c# wpf

所以我的UserControl包含ListViewButton。我已将UserControl添加到Window1.xaml,但我不知道该怎么办,因此我可以访问ListView中的Window1.xaml.cs控件。

我还需要做什么?这里最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

这不是你应该做的事情,而是在内部绑定的UserControl上创建属性,然后你有一个干净的界面。

e.g。

<UserControl Name="control" ...>
    <ListView ItemsSource="{Binding ItemsSource, ElementName=control}">
        <!-- ... -->
public class MyUserControl : UserControl
{
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(MyUserControl), new UIPropertyMetadata(null));
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
}
<Window ...>
    <local:MyUserControl x:Name="myUc"/>
        <!-- ... -->
myUc.ItemsSource = new string[] { "Lorem", "Ipsum" };