投射数据绑定值类型

时间:2013-03-19 04:40:16

标签: c# wpf data-binding casting

我有一个Slider控件和一个TextBlock,通过数据绑定显示Slider的值。

问题是它显示了一个浮点数,我对整数感兴趣。

我想将浮动转换为整数,因此我不会在45.25139664804483中看到TextBlock,而只会看到45

3 个答案:

答案 0 :(得分:3)

您可以在StringFormat绑定上使用TextBlock来格式化小数位

<StackPanel>
    <TextBlock Text="{Binding Value, ElementName=slider/>
    <TextBlock Text="{Binding Value, ElementName=slider, StringFormat={}{0:0}}" />
    <Slider x:Name="slider" />
</StackPanel>

结果:

enter image description here

答案 1 :(得分:1)

Slider_ValueChanged

上试试
textBox.Value = (int)Math.Ceiling(45.25139664804483);

答案 2 :(得分:0)

 private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
 {
      myTextBlock.Text = Convert.ToInt32(Math.Floor(e.NewValue));
 }

希望这会有所帮助。 有了绑定:

int _myValue;
public int MyValue{get{return _myValue;}set{_myValue = value; NotifyPropertyChanged("MyValue");}}

  private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
     {
          MyValue = Convert.ToInt32(Math.Floor(e.NewValue));
     }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

在这种情况下,您的类需要实现INotifyPropertyChanged接口

相关问题