Josef Lintz Josef Lintz - 3 years ago 176
C# Question

StringFormat freezes UI

I am making a ProgressBar with a TextBlock on top of it to notify the user about the download, I need the TextBlock to be bound to the value of the ProgressBar and formatted through XAML.

Like this:

<TextBlock x:Name="TxtBlock_Download" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="3"
TextAlignment="Center"
Foreground="White" Padding="0,2,0,0">
<!--Updates the textbox by using multibinding-->
<TextBlock.Text>
<!--TODO fix the StringFormat -->
<MultiBinding Converter="{StaticResource ResourceKey=kk}" StringFormat="{}{}">
<Binding ElementName="ProgressBar_Download" Path="Value"/>
<Binding ElementName="ProgressBar_Download" Path="Maximum"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>


I am also using a separate class to connect the two value and maximum

Like this:

class Binding : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0] + "/" + values[1].ToString();
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return (value as string).Split('/');
}
}


But every time I try to format the string using
StringFormat=""
it freezes the UI until the download is complete (The download still works in the background but the program is frozen).

Answer Source

Since you can't format numbers that have already been converted to string I recommend you simply rewrite your converter (since you already have one) to take care of all the formatting you need:

class MyAwesomeProgressConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return ((double)values[0]).ToString("f2") + "/" + ((double)values[1]).ToString("f2");
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        Enumerable.Repeat(DependencyProperty.UnsetValue, targetTypes.Length).ToArray()
    }
}

Also:

  • You don't need ConvertBack. Throw an Exception or return an Array of DependencyProperty.UnsetValue or Binding.DoNothing.
  • Don't name your Converter Binding - that might cause ambiguities
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download