我为我的应用程序编写了一个简单的UpDown UserControl。我在一个ListBox中渲染它,所以当UpDown控件被添加时,它们水平叠加。ListBox ItemTemplate是反复CLR和UserControl数据
我的UserControl有一个DependencyProperty,它对应于UpDown控件的内部数字,名为NumberProperty。
我通过数据绑定向ListBox添加了多个UpDown控件,其中ListBox的ItemsSource仅仅是一个ObservableCollection<NumberGroup>
,被称为NumberGroups
。每个NumberGroup
只有一个名为Number的成员,并且我希望此数字在呈现ListBox时出现在其各自的UpDown控件中。
我的列表框在XAML定义是这样的:
<ListBox Grid.Row="1" ItemsSource="{Binding NumberGroups}" ItemTemplate="{StaticResource NumberGroupTemplate}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Width="Auto" Height="Auto" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
和DataTemplate中为ListBox是:
<DataTemplate x:Key="RackTemplate">
<StackPanel Orientation="Vertical">
<TextBlock>Group</TextBlock>
<updown:UpDown Number="{Binding Number}" />
</StackPanel>
</DataTemplate>
这是一个有点混乱,因为我命名的DependencyProperty Number
沿着上下用户控件的与NumberGroup类中的属性相同。 NumberGroup仅仅是:
public class NumberGroup
{
public int Number { get; set; }
}
当我运行应用程序,我已经知道这行不通,因为输出窗口告诉我:
System.Windows.Data Error: 39 : BindingExpression path error: 'Number' property not found on 'object' ''UpDown' (Name='')'. BindingExpression:Path=Number; DataItem='UpDown' (Name=''); target element is 'UpDown' (Name=''); target property is 'Number' (type 'Int32')
OK,所以它绑定到用户控件,而不是ListItem ...不能写入。因此,作为测试,我从资源和列表框定义中删除了DataTemplate并重新运行它。在列表框中,我收到了一堆NumberGroup
,这正是我所期望的!
那么,当我这样做,它似乎绑定对ListItem,但是当我定义ItemTemplate它想要绑定到UpDown控件?任何解释将非常感激。我已经阅读了WPF博士的文章,并不明白为什么会发生这种情况。
UPDATE
好吧,我想通了有关我的问题的东西。在UserControl中,我将DataContext设置为自己,以便处理与Up和Down按钮相关的ICommand
。但由于某种原因,我还不明白,它与ListItem的数据绑定混淆!如果UserControl包含在ListItem中,为什么会发生这种情况?
感谢您的提示!就像你说的那样,它确实消除了指示绑定是UpDown UserControl而不是CLR数据的错误消息。现在我的问题是,我无法在我的UpDown控件中设置文本。我有一个用于Number的'DependencyProperty',因为我想要做一些像'',但它似乎不起作用。即使硬编码Number也不起作用,所以我认为我的DependencyProperty不起作用(但它在内部工作,因为我的向上和向下按钮命令可以更改数值!) –
Dave
2010-07-22 05:57:06
有趣的是,我将我的控件放到测试应用程序中,并通过窗口设置数字工作正常......但从我的UserControl(我有一个用户控件UserControl内)不设置它。 – Dave 2010-07-22 06:16:22
愚蠢的编码器错误,一切都很好,再次感谢您的有用提示! – Dave 2010-07-22 17:51:24