我爲我的應用程序編寫了一個簡單的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