WPF - 如何在代码后面的stackpanel / itemscontrol中与usercontrol进行交互?

时间:2017-12-02 10:46:18

标签: c# wpf xaml mvvm user-controls

我不确定如何提出这个问题,所以请告诉我需要澄清的内容!

我想创建一个相同结构的集合,包括usercontrol和remove按钮,并将它们存储在一个List of something中。

| <Some UserControl> | <Button> | <= grid   <= this is an ItemsTemplate instance
| <Some UserControl> | <Button> | <= grid
| <Some UserControl> | <Button> | <= grid

我可以在没有额外级别的'网格'的情况下使用删除按钮添加......但是一旦我添加了一个网格,我的数据模型和屏幕之间似乎断开连接(即,我可以不要从用户控件中提取数据。

我的主窗口有这个助手类,我的UserControl叫做PathThing。它在另一对文件中,但我认为这与我的问题无关。

我认为我的问题是PathEntry中的PathThing与显示的UserControl无关。

// I want this to represent 1 entry in the ItemsControl (DataTemplate instance)
public partial class PathEntry : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

    private PathThing m_path = new PathThing();

    public PathThing  Path
    {
        get
        {
            return m_path;
        }
        set
        {
            m_path = value;
            NotifyPropertyChanged();
        }
    }
}

MainWindow有这些成员:

    #region Paths
    private ObservableCollection<PathEntry> m_things = new ObservableCollection<PathEntry>();
    public ObservableCollection<PathEntry> PThings
    {
        get
        {
            return m_things;
        }
        set
        {
            m_things = value;
            NotifyPropertyChanged();
        }
    }
    #endregion

而Xaml就是这个

<ItemsControl Grid.Row="5" 
              Name="CPaths"
              ItemsSource="{Binding Path=PThings, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <local:PathThing Grid.Column="0" Question="What Do I write here to make this bind to PathEntry.Path?"></local:PathThing>
                <Button Grid.Column="1">Remove</Button>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

0 个答案:

没有答案