我有一个名为MessageElementControl
的用户控件。它包含在MessageElementContainerControl
中。当我打电话给MessageElementControl
时,我试图从容器传递一些属性,但这些属性未被设置。当我尝试在MessageElementControl
内使用它们时,它们为空。有问题的属性是ParentCollection
和ParentObject
。我这样做是为了当用户对MessageElementControl
进行更新或删除等操作时,我可以对集合进行必要的更改。这里是容器的XAML。问题是如何让这些属性获得正确的值?或者如果我应该采取完全不同的方法来处理整件事情?从itemscontrol到usercontrol的绑定
<UserControl x:Class="Bix.MessageElementContainerControl" Loaded="ThisControl_Loaded"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" x:Name="ThisControl" xmlns:my="clr-namespace:Bix"
>
<UserControl.Resources>
<ObjectDataProvider x:Key="MessageElementDataProvider" ObjectType="{x:Type my:MessageElementDataProvider}"/>
<ObjectDataProvider x:Key="MessageUIElements"
ObjectInstance="{StaticResource MessageElementDataProvider}"
MethodName="GetUIMessageElements"/>
<DataTemplate x:Key="MessageElement">
<my:MessageElementControl Width="{Binding ElementName=ThisControl,Path=Width}"
Element="{Binding Path=Element}"
ParentCollection="{Binding ElementName=ThisControl,Path=ItemsSource}"
ParentObject="{Binding ElementName=ThisControl,Path=ParentObjectSource}"/>
</DataTemplate>
</UserControl.Resources>
<StackPanel Height="Auto" Name="panel1">
<StackPanel Orientation="Horizontal" Height="Auto" Name="panel2">
<Label Content="Attachments and Data" FontSize="18" FontWeight="Bold" Foreground="#FF5A5A5A" Height="34" HorizontalAlignment="Left" Name="label6" VerticalAlignment="Top" Width="{Binding ElementName=ThisControl,Path=LabelWidth}" />
<Button Margin="0,4" Height="25" HorizontalAlignment="Left" Name="btnNew" Padding="3" VerticalAlignment="Top" Width="60" Click="btnNew_Click">
<TextBlock FontSize="12" FontWeight="Bold" Foreground="#FF3C3C3C" Text="New" TextWrapping="Wrap"/>
</Button>
</StackPanel>
<ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" Width="{Binding ElementName=ThisControl,Path=Width}">
<ItemsControl Name="itmsElements" Margin="0"
ItemsSource="{Binding Source={StaticResource MessageUIElements}}"
Width="{Binding ElementName=ThisControl,Path=Width}"
ItemTemplate="{Binding Source={StaticResource MessageElement}}">
</ItemsControl>
</ScrollViewer>
</StackPanel>
</UserControl>
UPDATE:found it。我正在使用ThisControl作为Container和包含的名称。所以绑定并没有真正发生。找到了一篇关于调试wpf绑定的有用文章,这些文章帮助我弄清楚了这一点。 devcomponents.com/blog/?p=312
尝试在您的视图模型中将'ItemsControl.ItemSource'绑定到'ObservableCollection'。集合中的每个更改都会立即更新控件。 –
这是一个可观察的事情..这是另一个问题。我在各地使用observables,而itemscontrol似乎并不在乎我何时对源集合进行更改。我需要重置ItemsSource以使其刷新UI。但在这个问题上的问题是由相互冲突的用户控件名称引起的。我正在使用ThisControl作为Container和包含的名称。找到了一篇关于调试wpf绑定的有用文章,这些文章帮助我弄清楚了这一点。 http://devcomponents.com/blog/?p=312 – Orson