Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于具有列表框的用户控件,如何将所选项目公开给父页面?_C#_.net_Wpf_Vb.net_Silverlight - Fatal编程技术网

C# 对于具有列表框的用户控件,如何将所选项目公开给父页面?

C# 对于具有列表框的用户控件,如何将所选项目公开给父页面?,c#,.net,wpf,vb.net,silverlight,C#,.net,Wpf,Vb.net,Silverlight,我有一个简单的用户控件,它将一些逻辑封装在自动完成框中。这个问题可能适用于任何ItemsControl控件,如下拉列表或列表框 <UserControl> <Grid Background="White"> <sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding myData}" /> </Grid> </UserControl> 我想在使用控

我有一个简单的用户控件,它将一些逻辑封装在自动完成框中。这个问题可能适用于任何ItemsControl控件,如下拉列表或列表框

<UserControl>
    <Grid Background="White">
        <sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding myData}" />
    </Grid>
</UserControl>

我想在使用控件的父级中公开自动完成框的
SelectedItem
属性。我的用户控件使用视图模型作为其数据上下文。否则,我想我可以将SelectedItem绑定到用户控件的依赖属性

我需要能够让父项在子项自动完成框所选项目更改时进行检测。我该怎么做呢?

只需在UserControl中创建一个,并将其与您的内部控制绑定,如下所示:

1) 在CustomControl中添加依赖项属性:

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

    // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(System.Collections.IEnumerable), typeof(UserControl1), new UIPropertyMetadata(null));
2) 使用dependency属性绑定内部控制:

<UserControl ... x:Name="control"     ... >

<ListBox ItemsSource="{Binding ElementName=control, Path=ItemsSource}" />  


编辑:实现ItemsSource

,如果您用这种方式尝试,它可以更新用户控件中的属性:

<ListBox SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWayToSource, Path=ThePropertyInMyUserControl}"/>


那么PropertyInMyUserControl可以是一个附加的依赖属性。

使用事件来处理怎么样?这样行吗?我不做MVCY你的意思是创建我自己的活动?我想我可以这样做,但是如果我可以的话,我想把一个属性从父对象中绑定出来。谢谢。这是有道理的,但我无法使绑定工作。我想获取所选项目,因此我像SelectedItem=“{binding ElementName=myACB,Path=SelectedItem,Mode=TwoWay}”一样进行绑定,并且我在控件类中设置了一个依赖项属性,类似于您所示,但用于SelectedItem。我在集合值上设置了一个中断集,但当我选择一个项目时,它不会影响代码。@亚当:我测试了它,它运行良好,只需确认SelectedItem的类型为[object],并且dependency属性的默认值为空即可。再试一次,告诉我发生了什么事。祝你好运如果不使用视图模型作为控件的数据上下文(
this.DataContext=new myControlViewModel();
),我可以让它工作。你知道为什么吗?