Visual Studio/WPF | CSharp > 속성 > set시 숫자인지 확인 > TryParse 사용 > 일부 실패

운영 환경
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community

string형 Mynumber에 대해서 수치가 아닌 경우에 set 하지 않게 해 본다.

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 _170612_t1540_isNumeric
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var data = new List<myList>();
            data.Add(new myList { Mynumber = "314" });
            data.Add(new myList { Mynumber = "pi" });
            data.Add(new myList { Mynumber = "2718" });
            uxMyNumbet.ItemsSource = data;
        }
    }

    public class myList
    {
        private string mynumber;
        public string Mynumber { get { return mynumber;  }
            set {
                if (Int32.TryParse(value, out Int32 wrk) == false)
                {
                    return;
                }
                mynumber = wrk.ToString();
            }
        }
    }
}


MainWindow.xaml
<Window x:Class="_170612_t1540_isNumeric.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170612_t1540_isNumeric"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="uxMyNumbet" Height="250"
                 DisplayMemberPath="Mynumber"/>
    </Grid>
</Window>




수치가 아닌("pi") 곳은 ""가 되어 버렸다.

좋은 웹페이지 즐겨찾기