开发者

How to force a refresh of the binding when bound to the entire object within a Template

开发者 https://www.devze.com 2023-04-12 12:16 出处:网络
I have a List of \'Rule\' classes that is the source of a DataGrid.In this example I have one of the columns which is a DataGridTemplateColumn that is bound to the \'Verified\' dependency property.

I have a List of 'Rule' classes that is the source of a DataGrid. In this example I have one of the columns which is a DataGridTemplateColumn that is bound to the 'Verified' dependency property.

The problem I am having is that I have a VerifyColorConverter where I wish to pass in the ENTIRE 'Rule' object of the selected row so I can examine the Rule instance and return an appropriate brush. I do this in when setting the background of the Border (see code below - Background="{Binding Converter={StaticResource convVerify}}")

<DataGridTemplateColumn Header="Verified" Width="150">
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Border Backgroun开发者_如何学Cd="{Binding Converter={StaticResource convVerify}}" 
                CornerRadius="4" Height="17" Margin="2,0,2,0" VerticalAlignment="Center" >
            <Grid>
                <TextBlock Foreground="Yellow" Text="{Binding Path=Verified, Mode=OneWay}" TextAlignment="Center" VerticalAlignment="Center" 
                        FontSize="11" FontWeight="Bold" />
            </Grid>
        </Border>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

This all works well when I set the source on the DataGrid but when the underlying 'Rule' object is altered the converter is not called upon so the brush stays the same. How can I force this to be updated when I alter some of the properties of the 'Rule' instance?

Any help appreciated!

Converter looks roughly like this:

    [ValueConversion(typeof(CRule), typeof(SolidColorBrush))]
public class VerifyColorConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        CRule rule = value as CRule;

        Color clr = Colors.Red;

        int count = 0;
        int verified = 0;

        if (rule != null)
        {
            count = rule.TotalCount;    
            verified = rule.NoOfVerified; 
        }

        if (count == 0) clr = Colors.Transparent;
        else if (verified == 0) clr = (Color)ColorConverter.ConvertFromString("#FFD12626");
        else if (verified < count) clr = (Color)ColorConverter.ConvertFromString("#FF905132");
        else clr = (Color)ColorConverter.ConvertFromString("#FF568D3F");

        SolidColorBrush brush = new SolidColorBrush(clr);
        return brush;
    }

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

    #endregion
}

EDIT

This is part of Rule class:

   /// <summary>
/// Compliance Restriction (Rule)
/// </summary>
public class Rule : BindElement
{
    public CMode Mode { get; private set; }
    public int RuleID { get; private set; }
    public string RuleDescription { get; private set; }

    private int _NoOfVerified = 0;
    private int _TotalCount = 0;

    public int NoOfVerified
    {
        get { return _NoOfVerified; }
        set { _NoOfVerified = value; RaiseChanged("Progress"); RaiseChanged("Verified"); }
    }

    public int TotalCount
    {
        get { return _TotalCount; }
        set { _TotalCount = value; RaiseChanged("Progress"); RaiseChanged("Verified"); }
    }

    public string Verified 
    {
        get 
        {
            if (TotalCount == 0) return "Nothing to verify";
            return string.Format("Verified {0} out of {1}", NoOfVerified, TotalCount); 
        }
    }


You could try using a MultiValueConverter instead of a regular Converter, and pass it whatever Rule Properties you need, or you can raise a CollectionChanged event when a property on the Rule gets changed. I usually prefer not to do this since I don't know how this affects performance, but it's an option.

Using a MultiConverter

public object Convert(object[] values, Type targetType,
    object parameter, System.Globalization.CultureInfo culture)
{
    Color clr = Colors.Red;

    int count = 0;
    int verified = 0;

    if (values.Count >= 2
        && int.TryParse(count, values[0].ToString()) 
        && int.TryParse(verfieid, values[1].ToString()))
    {
        if (count == 0) clr = Colors.Transparent;
        else if (verified == 0) clr = (Color)ColorConverter.ConvertFromString("#FFD12626");
        else if (verified < count) clr = (Color)ColorConverter.ConvertFromString("#FF905132");
        else clr = (Color)ColorConverter.ConvertFromString("#FF568D3F");
    }

    SolidColorBrush brush = new SolidColorBrush(clr);
    return brush;
}

XAML for MultiConverter:

<Border.Background>
    <MultiBinding Converter="{StaticResource convVerify}">
        <Binding Value="{Binding TotalCount}" />
        <Binding Value="{Binding NoOfVerified}" />
    </MultiBinding>
</Border.Background>

Using Property Change Events

RulesCollection.CollectionChanged += RulesCollection_Changed;

void RulesCollection_Changed(object sender, CollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(Rule rule in e.NewItems) // May need a cast here
            rule.PropertyChanged += Rule_PropertyChanged;

    if (e.OldItems != null)
        foreach(Rule rule in e.OldItems) // May need a cast here
            rule.PropertyChanged -= Rule_PropertyChanged;
}

void Rule_PropertyChanged()
{
    RaisePropertyChanged("RulesCollection");
}


OK - I found a way around this - what I have done is expose the object as a property and then call the OnPropertyChanged for this property whenever anything changes. This is picked up properly by the Bind object and handed over to the Converter whenever a property changes!!

    [Serializable()]
public class BindElement : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    [field: NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }

    public void RaiseChanged(string s)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(s));
    }

    #endregion
}

public class BindElement2 : BindElement
{
    public void RaiseChanged(string s)
    {
        base.RaiseChanged(s);
        NudgeMyself();
    }

    public void NudgeMyself()
    {
        base.RaiseChanged("Myself");
    }
}

   /// <summary>
/// Compliance Restriction (Rule)
/// </summary>
public class CRule : BindElement2
{
    public CMode Mode { get; private set; }
    public int RuleID { get; private set; }
    public string RuleDescription { get; private set; }

    private int _NoOfVerified = 0;
    private int _TotalCount = 0;

    public int NoOfVerified
    {
        get { return _NoOfVerified; }
        set { _NoOfVerified = value; RaiseChanged("Progress"); RaiseChanged("Verified"); }
    }

    public int TotalCount
    {
        get { return _TotalCount; }
        set { _TotalCount = value; RaiseChanged("Progress"); RaiseChanged("Verified"); }
    }

    public string Verified 
    {
        get 
        {
            if (TotalCount == 0) return "Nothing to verify";
            return string.Format("Verified {0} out of {1}", NoOfVerified, TotalCount); 
        }
    }

    public CRule Myself
    {
        get { return this; }
    }

and other classes can derived from BindElement2 and do the same: (create a property Myself that exposes the instance itself)

    public class CTradeRule : BindElement2
{
    public CRule Rule { get; set; }
    public bool IsLocked { get; set; }      // if true this should prevent a Reason from being given
    public bool IsVerified { get { return Reason.Length > 0; } }

    private string _Reason = "";        // ** no reason **
    public string Reason 
    {
        get { return _Reason; }
        set { _Reason = value; RaiseChanged("Reason"); }
    }

    public int Progress
    {
        get { return (IsVerified ? 1 : 0); }
    }

    public override string ToString()
    {
        return string.Format("Rule: {0}, Reason: {1}", Rule.RuleID, _Reason);
    }

    public CTradeRule Myself
    {
        get { return this; }
    }
}

Now in the xaml I can do this: (note the Binding Path=Myself) which then ensures the entire object is send to the converter WHENEVER any property changes!!

<DataGridTemplateColumn Header="Verified" Width="150">
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Border Background="{Binding Path=Myself, Converter={StaticResource convVerify}}" 
                CornerRadius="4" Height="17" Margin="2,0,2,0" VerticalAlignment="Center" >
            <Grid>
                <TextBlock Foreground="Yellow" Text="{Binding Path=Verified, Mode=OneWay}" TextAlignment="Center" VerticalAlignment="Center" 
                        FontSize="11" FontWeight="Bold" />
            </Grid>
        </Border>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

0

精彩评论

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

关注公众号