如何访问绑定到UserControl的ItemsControl的项目?

杰伊·坦南特

(我正在努力明确地问我的问题,如果不清楚,抱歉。)

我想访问已绑定到UserControl的ItemsControl的项目,但是我不知道它绑定到了什么属性。这是一个例子:

<ItemsControl ItemsSource="{Binding Path=Widgets}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:WidgetView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

其中“小部件”是以下类实例的集合:

public class Widget
{
    public int Data { get; set; }
    public int OtherData { get; set; }
    public Widget() {}
}

而“ WidgetView”是一个UserControl:

<UserControl x:Class="TestApp.WidgetView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestApp">
    <WrapPanel>
        <TextBlock Text="{Binding Path=Data, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="Set Other Data" Click="btn_clicked"/>
    </WrapPanel>
</UserControl>

后面有代码:

public partial class WidgetView : UserControl
{
    public WidgetView() {}
    private void btn_clicked(object sender, RoutedEventArgs e)
    {
        (???).OtherData = 42;
    }
}

在后面的代码中,我将如何访问ItemsControl中绑定到“ WidgetView”的“ Widget”实例?

布拉德利网

正如Crowcoder所说的;您通常会通过这样做,ICommand而无需进行任何代码隐藏。

话虽如此; 几次您需要此方法,就可以通过进行访问DataContext那是一个对象,所以您需要强制转换:

private void btn_clicked(object sender, RoutedEventArgs e)
    {
         var widget = (Widget)DataContext; //Or a safer cast!
         widget.OtherData = 42;
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将 ObservableCollection 的前 N 个项目绑定到 ItemsControl?

将列表绑定到ItemsControl:如何刷新

绑定到UserControl内部的UserControl

绑定到UserControl的问题

如何将 ItemsControl(网格外)绑定到网格?

如何将PreviewMouseDown绑定到ItemsControl中的FormattedText

如何将枚举ItemsControl绑定到WPF中的集合?

C# WPF MVVM - 如何从 ItemsControl/DataTemplate 访问特定项目?

将标签绑定到ItemsControl

如何将gridview绑定到UserControl的结果?

如何两种方式绑定到UserControl DependencyProperty?

如何将 UserControl 的属性绑定到属性?

如何将我的UserControl绑定到AvalonDock

UserControl绑定到Model属性

绑定到 UserControl 中的元素

将对象绑定到UserControl

如何在另一个UserControl中绑定到UserControl的属性?

WPF 绑定到 ItemsControl 的 ItemsPanel 的属性

从ItemsControl绑定到父DataTemplate属性

绑定到ItemsControl ItemTemplate内部的TextBox

无法将 ItemsControl 绑定到 ObservableCollection

将命令绑定到 ItemsControl 内的按钮

WPF-如何在UpdateSourceTrigger = Explicit时向数据绑定的ItemsControl添加/删除项目

如何将列表绑定到ItemsControl中的文本框

如何将 Expander 的 IsExpanded 属性绑定到 Items.Count 作为 ItemsControl in Style 的 Expander 内容

如何访问itemscontrol中的特定项目并在UWP中检索一些数据

在WPF中将UserControl绑定到MainWindow元素

将UserControl绑定到DataGrid中的数据

将UserControl属性绑定到Window属性