WPF 中的数据绑定和触发器兼容性
我有一个问题。我为 TreeView
制作了一个 DataTemplate
,我需要设置 ToggleButton
的 IsChecked
属性的初始值取决于我的型号。但事实证明,使用触发器/设置器设置此属性会禁用数据绑定。
是这样吗?如果是,请给我一个如何解决的建议?
<DataTemplate x:Key="CellTemplate_Name">
<DockPanel x:Name="dock">
<ToggleButton x:Name="Expander"
IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"> <--- Binding
...
<ToggleButton/>
...
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=ObjIsOpened, Converter={StaticResource DebugConverter}}" Value="true"> <--- Trigger
<Setter TargetName="Expander" Property="IsChecked" Value="true"></Setter>
</DataTrigger>
...
</DataTemplate.Triggers>
</DataTemplate>
问候,莱拉克斯。
I have a problem. I made a DataTemplate
for a TreeView
and I need to set the initial value of the ToggleButton
's IsChecked
property depending on my model. But it turns out that setting this property using triggers/setters disables the databinding.
Is it so? If yes, give me a suggestion how it can be fixed?
<DataTemplate x:Key="CellTemplate_Name">
<DockPanel x:Name="dock">
<ToggleButton x:Name="Expander"
IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"> <--- Binding
...
<ToggleButton/>
...
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=ObjIsOpened, Converter={StaticResource DebugConverter}}" Value="true"> <--- Trigger
<Setter TargetName="Expander" Property="IsChecked" Value="true"></Setter>
</DataTrigger>
...
</DataTemplate.Triggers>
</DataTemplate>
Regards, Lerax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先我建议你阅读 Josh Smith 的精彩文章
使用 ViewModel 模式简化 WPF TreeView
根据该文章,我会建议为
TreeViewItem
定义一个样式(使用TreeView
的ItemContainerStyle
属性),将其IsExpanded
属性绑定到您的模型对象的ObjIsOpened
属性。然后摆脱你的扳机。例子:
First of all I suggest you read the excellent article by Josh Smith
Simplifying the WPF TreeView by Using the ViewModel Pattern
Based on that article, I would suggest defining a style for the
TreeViewItem
(using theItemContainerStyle
property of theTreeView
) which binds itsIsExpanded
property to your model object'sObjIsOpened
property. Then get rid of your trigger.Example:
我怀疑他们不会禁用数据绑定,他们只是具有更高的优先级。与其同时使用绑定和触发器,为什么不使用其中之一(绑定或触发器)?例如,您可以直接绑定到模型,并且根本不使用触发器......
I suspect they do not disable data binding, they just have higher priority. Instead of using binding and trigger at the same time, why don't you use one of them (either binding or trigger)? E.g. you could bind to model directly, and don't use trigger at all...