我有一個Silverlight模板控件(不是用戶控件),它包含一個ListBox。在Silverlight模板控件的ListBox DataTemplate中訪問按鈕點擊按鈕
在ListBox中我有一個按鈕的DataTemplate中,像這樣:
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ProgressBar Grid.Column="0" Width="70" Height="20" Value="{Binding Path=Percentage}" Minimum="0.0" Maximum="100.0" />
<TextBlock Grid.Column="0" Text="{Binding Path=Percentage, StringFormat='{}{0:##0.0}%'}" Margin="10,3,3,3" HorizontalAlignment="Center" />
<TextBlock Grid.Column="1" Text="{Binding Path=File.Name}" Margin="3" />
<Button Grid.Column="2" Content="Remove" x:Name="RemoveButton" Command="{TemplateBinding DeleteCommand}" Style="{TemplateBinding UploadButtonStyle}" HorizontalAlignment="Right" Margin="0,0,5,0" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
看到按鈕出現在模板的結束?我如何訪問它的點擊事件?我不能使用GetTemplateChild()方法,因爲按鈕是DataTemplate的一部分。我試過了Commanding(正如你上面看到的)。似乎這是要走的路,儘管模板控制不完全是MVVM。
任何想法?也許是指揮之外的東西?否則我在指揮錯誤?
這裏的一些相關代碼:
...依賴屬性/屬性定義...(?它應該是一個德普道具)
public static readonly DependencyProperty DeleteCommandProperty =
DependencyProperty.Register("DeleteCommand", typeof(ICommand), typeof(MultipleFileUpload), new PropertyMetadata(null));
public ICommand DeleteCommand
{
get { return (ICommand)GetValue(DeleteCommandProperty); }
set
{
SetValue(DeleteCommandProperty, value);
FirePropertyChanged("DeleteCommand"); //INotifyPropertyChanged stuff
}
}
...在OnApplyTemplate().. 。
public override void OnApplyTemplate()
{
....
DeleteCommand = new DelegateCommand(RemoveItemFromList, CanRemove);
....
base.OnApplyTemplate();
}
...的ICommand的行動......
private void RemoveItemFromList(object commandParameter)
{
//NEVER GETTING HERE!
}
我希望它是小事。
謝謝大家!
凱文
以下是XAML中如何將列表框放在一起的簡要說明:http://blogs.msdn.com/b/mikehillberg/archive/2006/09/28/briefanatomyofalistbox.aspx – Aardvark 2011-04-13 15:34:51
謝謝對於這個建議。我正在嘗試第二種方法。快速的問題 - 在我的派生ContentPresenter(我以前從來沒有得到的其中之一..)我如何設置命令屬性等於從ItemControl的人?對不起,感謝您的幫助。 – kmk 2011-04-13 15:41:06
它在派生的ItemsControl中創建派生ContentPresenter的新實例。您可以在ItemsControl.GetContainerForItemOverride()中執行此操作。我會嘗試編輯答案... – Aardvark 2011-04-13 15:57:41