滑块控件和正文块控制交互地铁应用(slider control and textblock cont

2019-10-29 12:18发布

我试图通过设置绑定{}在XAML滑块控件,从文本块的文本属性值。

<Slider   ValueChanged="slider_ValueChanged_1"    Value= "{Binding ElementName=ComponentTextBlockValue,Path=Text}"   StepFrequency="25"/>  

我是否需要转换器来设置滑块的值。 的结合似乎有时工作,但有时这是行不通的。 有时候,滑块只是没有将其值设置为文本框的值。

Answer 1:

既然你没有直接的值转换器滑块绑定的价值,我怀疑是结合坏了当文本不是数字或超出范围。

您可以防止通过创建一个值转换器,以防止被束缚不好的价值,所以绑定将始终工作。

下面是一些例子:

public class TextToSliderValueConverter : IValueConverter
{
    public double MaximumSliderValue { get; set; }
    public double MinimumSliderValue { get; set; }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        double sliderValue;

        if (double.TryParse(value as string, out sliderValue)
            && sliderValue <= MaximumSliderValue && sliderValue >= MinimumSliderValue)
        {
            return sliderValue;
        }
        else
        {
            return 0.0;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

这里是XAML:

<Page
    x:Class="stovfSliderTextBox.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:stovfSliderTextBox"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <local:TextToSliderValueConverter x:Key="txtToSliderValue" MaximumSliderValue="100" MinimumSliderValue="0"/>
    </Page.Resources>
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel>
            <Slider Value= "{Binding ElementName=ComponentTextBlockValue,Path=Text, Converter={StaticResource txtToSliderValue}, ConverterParameter=slider}" StepFrequency="25"/>
            <TextBox x:Name="ComponentTextBlockValue" Width="50"/>
        </StackPanel>
    </Grid>
</Page>

该TextToSliderValueConverter确保滑块总是会得到有效的价值。 如果你不使用默认的Slider.Maximum或Slider.Minimum,您可以修改相应的值。

希望这可以帮助!



文章来源: slider control and textblock control interaction-Metro apps