【发布时间】:2014-06-30 13:15:23
【问题描述】:
我正在尝试使用 WPF 构建一个 GUI,我可以在其中绘制一些基本形状并将它们存储到一个 xml 文件中。形状是在 xaml 文件中设计的,我为每个形状添加了标签。现在我想在我的代码中获取它们标签的值,以将其作为属性存储在输出 xml 文件中。
例如,我在我的 xaml 文件中创建了一个带有名为“RectangleTag”的标签的矩形,如下所示:
<Style x:Key="stack" TargetType="Rectangle" BasedOn="{StaticResource FlowChartRectangleStyle}"/>
<Style x:Key="stack_DragThumb" TargetType="Rectangle" BasedOn="{StaticResource stack}">
<Setter Property="IsHitTestVisible" Value="true"/>
<Setter Property="Tag" Value="RectangleTag"/
</Style>
和
<Rectangle Style="{StaticResource stack}" ToolTip="stack" StrokeThickness="2">
<s:DesignerItem.DragThumbTemplate>
<ControlTemplate>
<Rectangle Style="{StaticResource stack_DragThumb}" x:Name="StackShape" Tag="RectangleTag" />
</ControlTemplate>
</s:DesignerItem.DragThumbTemplate>
</Rectangle>
然后在我的代码中我做了:
XElement myItem = new XElement("Items",
from item in designerItems
let contentXaml = XamlWriter.Save(((DesignerItem)item).Conent)
select new XElement("Item",
new XAttribute( "Tag", item.Tag.ToString())
);
然后我的 GUI 停止响应这一行。我相信必须有某种方法可以在这里获取标签,但显然不是以这种方式。我怎样才能做到这一点?不一定是标签,x:Name 或 x:Key 也足以让我区分给定的形状。
我也试过这条线:
new XAttribute("Tag", item.Name)
但这会给出一个空字符串,而不是在 xaml 文件中分配的名称。有人可以帮忙吗?谢谢。
【问题讨论】:
-
很抱歉通知您这件事,但到目前为止您的做法是错误的。 WPF 是一种以数据 为中心的语言。我们使用绑定到 UI 元素的数据的 data 元素。如果您正确地做到了这一点,那么您将拥有一些具有数据绑定属性的不错的类,因此读取
Tag值将像这样简单:object tagValue = element.Tag; -
感谢您的回复。我还没有正确完成,可能是因为你提到的原因。但是你有什么建议吗?