How do I create a ProgressBar which is hidden when the Value is 0?
The following doesn't quite work (ProgressValue is a value set in DataContext.)
<StatusBarItem Grid.Column="1">
<StatusBarItem.Resources>
<Style TargetType="ProgressBar">
<Style.Triggers>
<DataTrigger Binding="开发者_运维知识库{Binding ProgressValue}" Value="0">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StatusBarItem.Resources>
<ProgressBar Value="{Binding ProgressValue}" Grid.Column="1" Width="80" Height="13">
</ProgressBar>
</StatusBarItem>
Try setting the ProgressBar's Visibility
property in its ValueChanged
event:
private void progressBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
progressBar1.Visibility = (progressBar1.Value == 0) ? Visibility.Hidden : Visibility.Visible;
}
Try specifying a Minimum (and Maximum) value. After setting those it seems to work for my version of your code.
With this XAML:
<StatusBarItem x:Name="Feedback" Grid.Row="1">
<StatusBarItem.Resources>
<Style TargetType="ProgressBar">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="0">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StatusBarItem.Resources>
<ProgressBar Value="{Binding Mode=OneWay}" Minimum="0" Maximum="10" Grid.Column="1" Width="80" Height="13">
</ProgressBar>
</StatusBarItem>
and this code in the constructor of MainWindows.xaml.cs (for testing purposes only)
int value = 10;
public MainWindow()
{
InitializeComponent();
Feedback.DataContext = value;
Timer t = new Timer(500);
t.Elapsed += (s, e) =>
{
if (value > 0) Dispatcher.Invoke(new Action(() => { Feedback.DataContext = --value; }));
else t.Stop();
};
t.Start();
}
I get the progress bar to go from 10 down to 0 at which point the progress bar disappears.
Example XAML:
<ProgressBar>
<ProgressBar.Resources>
<src:DoubleToVisibilityConverter x:Key="_doubleToVisibilityConverter" />
</ProgressBar.Resources>
<ProgressBar.Visibility>
<Binding
RelativeSource="{RelativeSource Self}"
Path="Value"
Converter="{StaticResource _doubleToVisibilityConverter}"
/>
</ProgressBar.Visibility>
</ProgressBar>
And code:
public class DoubleToVisibilityConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double input = 0;
if (value is double)
{
input = (double)value;
}
else if (value is int)
{
input = (int)value;
}
else if (value is string) // Useful if input of converter is written in XAML
{
if (!double.TryParse((string)value, out input))
return Binding.DoNothing;
}
else
{
return Binding.DoNothing;
}
return (input > 0 ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
Disclaimer: written from memory, not compiled or tested.
精彩评论