What is the order of setting properties in XAML?

落爺英雄遲暮 提交于 2021-02-10 06:15:21

问题


I have a TextBlock with two properties (Text and Foreground) bound to the same ViewModel property.

Both also have converters. One of the converters checks the Text property and returns a 'dash' if the value is NaN. The other checks that the value is above, below or equals zero and accordingly sets the foreground to different colors.

XAML example:

<TextBlock>

       <TextBlock.Text>
            <Binding Path="AvgDistance" StringFormat="{}{0:N1}"                        
                  Converter="{x:Static converter:ValueToDash.Instance}"/>
       </TextBlock.Text>        

       <TextBlock.Foreground>                                                    
          <MultiBinding Converter="{x:Static converter:ValueToColor.Instance}">                                                       
             <Binding Path="AvgDistance"/>
             <Binding ElementName="currentPeriod" Path="IsChecked" />
           </MultiBinding>
       </TextBlock.Foreground>  

</TextBlock>

Now I need that the ValueToDash converter fired before the ValueToColor converter, but it is always vice versa.

The Foreground property seems to be always set first, and only then the Text property is set.

Why is it so? And is it possible to reverse the order of setting?


回答1:


You shouldn't rely on the order in which the properties are being set.

What you could do instead is to add another binding to your MultiBinding that binds to the Text property of the TextBlock:

<TextBlock>

    <TextBlock.Text>
        <Binding Path="AvgDistance" StringFormat="{}{0:N1}"                        
                  Converter="{x:Static converter:ValueToDash.Instance}"/>
    </TextBlock.Text>

    <TextBlock.Foreground>
        <MultiBinding Converter="{x:Static converter:ValueToColor.Instance}">
            <Binding Path="AvgDistance"/>
            <Binding ElementName="currentPeriod" Path="IsChecked" />
            <Binding Path="Text" RelativeSource="{RelativeSource Self}"/>
        </MultiBinding>
    </TextBlock.Foreground>

</TextBlock>

Then the ValueToColor converter will be invoked (again) whenever the Text property is set to some new value.



来源:https://stackoverflow.com/questions/52331809/what-is-the-order-of-setting-properties-in-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!