开发者

Set property on the parent control from a data template

How can I set a property on a parent/ancestor control from a data template?

The only way I can think of is to create a dummy invisible control on my form and then bind one of the properties with the correct default value using a converter, onewaytosource and relativesource findancestor开发者_运维问答 binding which is a pretty horrible solution.

What I'd like to do is to be able to have the setter target a different control in much the same way you can use a binding with a different source.


Few possible options: 1) On the binding inside DataTemplate, set the source to be the parent using ElementName, and bind using OneWayToSource. This will transfer the value from the binding target (the element inside the DataTemplate) to the binding source (the parent control) 2) Use a common object that both the DataTemplate and the control bind to. The DataTemplate will bind to it using OneWayToSource and the control will bind to it with OneWay. It can even be a resource, so you can access it from XAML. 3) Use RelativeSource and FindAncestor. 4) Use some kind of a routed event, and handle it at the control level. It will be fired from the data template by an attached behavior (google it!). The event will deliver the data and the event handler will set the relevant property on the control.

Options 1,3 are similar to what you suggested. Options 2, 4 are different. In terms of elegancy, I prefer option 2.

In addition - be aware of conflicts in all solutions. If the DataTemplate is instanciated many times inside a single control all the instances will attempt to set the property of the control. The effect will be the effect of the last executed set attempt and it can be problematic in some cases if you can't control their order.

Alex.


Assuming that your ancestor is internal to the data template, you can give a name to that ancestor using the "Name" property. Once it has a name, you can use the "TargetName" of the setter to specify that ancestor.

Example:

<DataTemplate>
    <Grid Name="ControlGrid">
        <Path x:Name="Arrow" Fill="Black">
            <Path.Triggers>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Visibility" TargetName="ControlGrid" Value="Collapsed"/>
                </Trigger>
            </Path.Triggers>
        </Path>
    </Grid>
</DataTemplate>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜