teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記

2019/05/01 06:27

投稿

Zuishin
Zuishin

スコア28675

answer CHANGED
@@ -1,3 +1,84 @@
1
1
  バインドするデータが文字列でいいなら XAML の方は特別な工夫は入りません。その文字列をプロパティに持つクラスを作り、普通にバインドしてください。
2
2
 
3
- クラスの方でプロパティのセッターを工夫し、何か値が入れられたらそれを検証してプロパティの値を調整するようにしてください。
3
+ クラスの方でプロパティのセッターを工夫し、何か値が入れられたらそれを検証してプロパティの値を調整するようにしてください。
4
+
5
+ # 追記
6
+
7
+ XAML
8
+ ```C#
9
+ <Window x:Class="WpfApp1.MainWindow"
10
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
11
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
12
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
13
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
14
+ xmlns:local="clr-namespace:WpfApp1"
15
+ mc:Ignorable="d"
16
+ Title="MainWindow" Height="450" Width="800">
17
+ <Window.DataContext>
18
+ <local:ViewModel/>
19
+ </Window.DataContext>
20
+ <Grid>
21
+ <Grid.RowDefinitions>
22
+ <RowDefinition Height="Auto"/>
23
+ <RowDefinition/>
24
+ </Grid.RowDefinitions>
25
+ <Grid.ColumnDefinitions>
26
+ <ColumnDefinition/>
27
+ <ColumnDefinition Width="Auto"/>
28
+ </Grid.ColumnDefinitions>
29
+ <TextBox Grid.Row="0" Grid.Column="0" Text="{Binding TextValue}"/>
30
+ <Button Grid.Row="0" Grid.Column="1">Click</Button>
31
+ </Grid>
32
+ </Window>
33
+ ```
34
+
35
+ ViewModel.cs
36
+ ```C#
37
+ using System;
38
+ using System.Collections.Generic;
39
+ using System.ComponentModel;
40
+ using System.Runtime.CompilerServices;
41
+
42
+ namespace WpfApp1
43
+ {
44
+ public class ViewModel : INotifyPropertyChanged
45
+ {
46
+ #region INotifyPropertyChanged
47
+ public event PropertyChangedEventHandler PropertyChanged;
48
+ protected virtual void OnPropertyChanged(string propertyName)
49
+ {
50
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
51
+ }
52
+ protected bool SetProperty<T>(ref T field, T value, [CallerMemberName]string propertyName = null)
53
+ {
54
+ if (EqualityComparer<T>.Default.Equals(field, value)) return false;
55
+ field = value;
56
+ OnPropertyChanged(propertyName);
57
+ return true;
58
+ }
59
+ #endregion
60
+
61
+ private string textValue;
62
+ public string TextValue
63
+ {
64
+ get => textValue;
65
+ set
66
+ {
67
+ if (DateTime.TryParse(value, out DateTime dateTime))
68
+ {
69
+ value = dateTime.ToString("yyyy/MM/dd");
70
+ }
71
+ else if (int.TryParse(value, out int i))
72
+ {
73
+ value = i.ToString("N0");
74
+ }
75
+ else if (double.TryParse(value, out double d))
76
+ {
77
+ value = d.ToString("N2");
78
+ }
79
+ SetProperty(ref textValue, value);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ ```