简体   繁体   English

是否可以使用WPF将元素的可见性属性绑定到XML?

[英]Is it possible to bind the visibility property of an element to an XML with WPF?

I have an XML containing lots of information, but there are some informations that isn't supposed to be shown unless it exists in the xml. 我有一个包含很多信息的XML,但是有些信息除非它存在于xml中,否则不应该显示。 I know I can do this manually, but it's not good. 我知道我可以手动执行此操作,但这不是很好。

imagine the xml something like this: 想象一下这样的xml:

<root>
    <MandatoryContent />
    <OptionalContent />
</root>

I want to bind a button's visibility property to the existence of the OptionalContent element. 我想将按钮的可见性属性绑定到OptionalContent元素的存在。 Is it possible? 可能吗?

You can bind your element directly to the object it represents and then use a converter to set the visibility to Visibility.Visible when not null. 您可以将元素直接绑定到其表示的对象,然后使用转换器将可见Visibility.Visible设置为Visibility.Visible不为null时)。

 <Label Visibility="{Binding MyObject, Converter={StaticResource NullToVisibilityConverter}} />

Be sure to declare your converter in the ressources 确保在资源中声明您的转换器

<win:CustomWindow.Resources>
    <Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
</win:CustomWindow.Resources>

And if you want a good example of converter, here is IValueConverter from MSDN http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx 如果您想要一个很好的转换器示例,请访问MSDN http://msdn.microsoft.com/zh-cn/library/system.windows.data.ivalueconverter.aspx ,这里是IValueConverter。

You can't bind directly to XML, but you can use something to create objects from XML. 您不能直接绑定到XML,但是可以使用某些东西从XML创建对象。

LinqToXSD is a good candidate here. LinqToXSD是一个很好的候选人。

It works like this: You create Xml Schema, LinqToXSD creates classes based on your schema, then you can read the XML and it will create the whole object tree based on your XML. 它的工作方式如下:创建Xml Schema,LinqToXSD根据您的模式创建类,然后您可以读取XML,它将基于XML创建整个对象树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM