WPF值转换实例

WPF绑定功能非常方便,有时候点击某值时在另t一处显示此值的另一表现形式或调用其对应的其它值,用WPF值转换功能会很方便,下面就一LISTBOX和TEXTBLOCK控件,把LISTBOX中的值转换成除以1000后的结果显示在TextBlock中

 

1、值转换类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace WpfApplication4
{
    class MyValueConvert:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                int v = int.Parse(value.ToString());
                return v / 1000 + "M";
            }
            catch (Exception ex)
            {
                return Binding.DoNothing;
            }
        }

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

2、主窗口C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication4
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<string> obj = new ObservableCollection<string>();
        public MainWindow()
        {
            InitializeComponent();

            obj.Add("1000");
            obj.Add("10000");
            obj.Add("100000");
            obj.Add("10000000");
            obj.Add("100000000");
            this.listbox.ItemsSource = obj;
        }
    }
}

3、显示界面

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MyValueConvert x:Key="myCvt"></local:MyValueConvert>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <TextBlock Name="tb" Margin="20" Text="{Binding ElementName=listbox,Path=SelectedItem,Converter={StaticResource myCvt}}"></TextBlock>
            <ListBox Name="listbox"/>       
        </StackPanel>
    </Grid>
</Window>

 

转载于:https://www.cnblogs.com/lunawzh/p/5853896.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值