【发布时间】:2016-09-03 09:50:16
【问题描述】:
我在这里尝试做的是将按钮包含的对象绑定到我的 ViewModel 中的属性以便使用它,但无法解决我的问题。我阅读了 Tag 属性,但无法完全理解它是如何绑定的以及如何使用它。
我的按钮:
<DataTemplate x:Key="Template">
<GroupBox>
<WrapPanel>
<Button x:Name="Button"
FontSize="10"
Height="80" Width="80"
Content="{Binding Name}"
</Button>
</WrapPanel>
</GroupBox>
</DataTemplate>
我用来自 ObservableCollection 的数据填充我的按钮
<WrapPanel x:Name="OrderButtons"
VerticalAlignment="Bottom">
<ScrollViewer x:Name="OrderButtons1"
Margin="3">
<ItemsControl
ItemTemplate="{StaticResource OrderTemplate}"
ItemsSource="{Binding Source={StaticResource ObservableCollectionWithData}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal">
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</WrapPanel>
我的视图模型
public class OrderViewModel : ObservableCollection<Order>
{
public Item OrderItem{ get; set; }
public OrderViewModel()
{
}
}
我应该怎么做才能将我的 Button 绑定到我的 ViewModel 的 OrderItem 属性中?
我尝试的是:
<Button x:Name="OrderButton"
FontSize="10"
Height="80" Width="80"
Content="{Binding Name}"
Tag="{Binding OrderItem, Source={StaticResource OrderViewModel}}"
</Button>
【问题讨论】:
-
您的 itemscontrol 是否遇到任何绑定错误?
-
完全没有错误,我运行我的应用程序并且一切都很顺利,直到我单击按钮并使用命令尝试查看它是否正确绑定对象。我从源中的按钮中删除的是一个命令,它触发 MessageBox 并尝试在其中打印 OrderItem.Name 以查看是否正确绑定。它的作用是触发一条消息:对象引用未设置为对象的实例。这意味着 OrderItem 是空的。
-
BTW 绑定错误不像异常,它们会打印到输出中。
-
你好。我能够将我的按钮与我的 ViewModel 中的 ObservableCollection 属性绑定,但我现在的问题是如何知道单击了哪个按钮,所以我可以使用绑定到确切按钮的对象。我已经使用我的 CommandParameter 从另一个控件发送信息列表,所以我不能使用它。有任何想法吗?谢谢!