开发者

Change made in the Converter will notify the change in the bound property?

I have two property FirstName and LastName and bound to a textblock using Multibinidng and converter to display the FullName as FirstName + Last Name.

FirstName="Kishore" LastName="Kumar"

In the Converter I changed the LastName as "Changed Text"

values[1] = "Changed Text";

After executing the Converter my TextBlock will show "Kishore Changed Text" but Dependency property LastName is still have the last value "Kumar". Why I am not getting the "Changed 开发者_如何转开发Text" value in the LastName property after the execution?.

Will the change made at converter will notify the bound property?

 <Window.Resources>
    <local:NameConverter x:Key="NameConverter"></local:NameConverter>
</Window.Resources>
<Grid>
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource NameConverter}">
                <Binding Path="FirstName"></Binding>
                <Binding Path="LastName"></Binding>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
 </Grid>

Converter:

 public class NameConverter:IMultiValueConverter
{
    #region IMultiValueConverter Members

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        values[1] = "Changed Text";
        return values[0].ToString() + " " + values[1].ToString();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}


Will the change made at converter will notify the bound property?

No. Converters are used to convert bound values - not modify them. You should be doing that in a more appropriate location, such as in dependency property coercion or in your view model.


The object[] you get as parameter in the Convert method are the property values after the two bindings have been evaluated. The values of the properties have been copied into the array, and by assigning values to the elements, you are only changing the array, not the Properties the values come from.

If you want to change the original object that has those properties, you could create a normal valueconverter for that class and bind to the object itself. like this:

public class NameConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Person p = value as Person;
        if (p == null) { return null; }
        p.LastName = "Changed Text";
        return p.FirstName + " " + p.LastName;
    }
// ...
}

Of course, there would be no need for a MultiBinding then. You could just bind to the object itself:

<TextBlock Text="{Binding Converter={StaticResource NameConverter}}"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜