簡體   English   中英

WPF:ItemsControl和DataContext

[英]WPF: ItemsControl and DataContext

我有一個主窗口,里面有一個用戶控件,名為SuperMode SuperMode由一組人組成,此集合中的每個人都有自己的任務集合。 聽起來很簡單吧?

從文件SuperMode.xaml

<UserControl 
    x:Class="Prototype.SuperMode"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Prototype"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"> <!-- NOTE! -->
    <!-- Look at how I'm setting the DataContext, as I think it's
         important to solve the problem! -->

    <ScrollViewer CanContentScroll="True">
        <ItemsControl ItemsSource="{Binding People}" Margin="1">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="1"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </ScrollViewer>

</UserControl>

這很好,我可以看到個人,我期待! 現在,我所要做的就是為Person用戶控件獲取XAML,以便同時顯示所有任務。

如您所見,我正在使用People屬性用項填充控件。 People屬性的類型為ObservableCollection<Person> ,其中Person是另一個用戶控件,如此...

來自Person.xaml

<UserControl 
    x:Class="Prototype.Person"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Prototype">

    <Border Background="Black" CornerRadius="4" Margin="1">
        <ItemsControl ItemsSource="{Binding Tasks}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Border>

</UserControl>

這里的TasksPerson的屬性,類型為ObservableCollection<Task> 這是卡住的地方! 顯然WPF無法找到任何Tasks屬性並查看VS2008的輸出窗口,我發現以下內容:

System.Windows.Data錯誤:39:BindingExpression路徑錯誤:'object'''SuperMode'(Name ='SuperMode')'上找不到'Tasks'屬性。 BindingExpression:路徑=任務; DataItem ='SuperMode'(Name ='SuperMode'); target元素是'ItemsControl'(Name =''); target屬性是'ItemsSource'(輸入'IEnumerable')

現在我迷路了。 看來我必須在每個Person上設置DataContext屬性,否則它仍然認為數據上下文是SuperMode ,但我該怎么做呢?

忽略你所擁有的相當不愉快的設計(你應該研究MVVM),你應該能夠為子UserControl設置DataContext ,如下所示:

<ItemsControl ItemsSource="{Binding People}" Margin="1">
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="FrameworkElement.DataContext" Value="{Binding RelativeSource={RelativeSource Self}}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM