【发布时间】:2015-05-10 10:57:41
【问题描述】:
我已经看到一些关于 WP8 或其他的答案,但似乎 WP8.1 中没有触发器(或者我遗漏了什么?)
我有一个从代码绑定的数据模板(它是一个集线器数据模板,我混合了静态和动态集线器部分,因此需要从代码中设置此数据模板)。
此数据模板在单独的 xaml 文件中定义,它包括一个列表框(或列表视图)以及为项目定义的另一个数据模板。
我需要在项目的点击或列表框选择更改(或等效的东西)上绑定命令。但是,模板中定义的点击事件没有被调用,因此我想到了在 UI 元素上绑定命令,但是这些似乎不支持命令和交互触发器。
关于如何处理的任何线索? :)
在下面的示例中,我没有收到事件 Item_Tapped 或 ListBox_SelectionChanged,无论如何我更愿意将其中一个绑定到视图模型中的命令。
<DataTemplate x:Key="HubSectionTemplate">
<Grid>
<ListBox ItemsSource="{Binding MyNodes}"
SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="64" Tapped="Item_Tapped" >
<TextBlock Text="{Binding MyText}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
这是从代码中使用它的方式:
HubSection hs = new HubSection()
{
ContentTemplate = Application.Current.Resources[HUBSECTION_TEMPLATE] as DataTemplate,
DataContext = model,
Tag = model.UniqueId,
};
Hub.Sections.Insert(firstSectIdx + 1, hs);
public class Model
{
public Guid UniqueId {get;set;}
public List<ItemModel> MyNodes {get;set;}
}
public class ItemModel
{
public string MyText {get;set;}
}
PS:ItemModel 是在另一个程序集中定义的,因此不应编辑(如果可能,该命令应在 Model 类中)
--- 编辑 ---
为了简化问题,我使用以下模型:
public class Model
{
public Guid UniqueId {get;set;}
public List<ItemModel> MyNodes {get;set;}
public ICommand MyCommand {get;set;}
}
public class ItemModel
{
Model _Model;
public ItemModel(Model m) {_Model = m; }
public string MyText {get;set;}
public ICommand MyCommand { get { return _Model.MyCommand; }}
}
而我的(临时)解决方案是在 itemtemplate 中使用一个按钮:
<ListView.ItemTemplate>
<DataTemplate>
<Button HorizontalAlignment="Stretch" Command="{Binding TapCommand}" Height="64">
<TextBlock Text="{Binding MyText}" />
</Button>
</DataTemplate>
</ListView.ItemTemplate>
【问题讨论】:
-
不直接使用 StackPanel,将其包装在样式按钮中怎么样?这样,您就拥有了可用于拦截点击的 Button Command 绑定。另一件事,您要求点击项目或更改选择。请注意,两者的行为不同,如果您选择两次相同的项目,点击会触发,但更改的选择不会。
-
关于行为这并不重要,因为我正在构建类似文件资源管理器的东西,因此如果点击该项目,应该会发生一些事情并且不能发生两次。如果我没有找到任何其他选项,我将使用按钮结束,但我真的不喜欢在不应该是一个按钮时使用它。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
我同意“一般”,但这是一个非常具体的问题,因为我已经能够在其他 XAML 平台上处理这个问题,但在 WP8.1 上却没有。这就是为什么我在标题中指定它,因为它很重要。
标签: c# xaml windows-phone-8.1