Vâng, đây là ví dụ đơn giản về cách thực hiện điều này với MVVM.
Thứ nhất viết một cái nhìn mô hình:
public class SimpleViewModel : INotifyPropertyChanged
{
private int myValue = 0;
public int MyValue
{
get
{
return this.myValue;
}
set
{
this.myValue = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Sau đó viết một bộ chuyển đổi, vì vậy bạn có thể dịch chuỗi của bạn để int và ngược lại
[ValueConversion(typeof(int), typeof(string))]
class SimpleConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int returnedValue;
if (int.TryParse((string)value, out returnedValue))
{
return returnedValue;
}
throw new Exception("The text is not a number");
}
}
Sau đó viết mã XAML của bạn như thế này:
<Window x:Class="StackoverflowHelpWPF5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:[YOURNAMESPACEHERE]"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:SimpleViewModel></local:SimpleViewModel>
</Window.DataContext>
<Window.Resources>
<local:SimpleConverter x:Key="myConverter"></local:SimpleConverter>
</Window.Resources>
<Grid>
<TextBox Text="{Binding MyValue, Converter={StaticResource myConverter}, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</Grid>
Nguồn
2015-09-14 13:23:11
bạn đang cố gắng để chuyển đổi các đầu vào cho một số? –
@crossemup Nếu bạn muốn lưu trữ giá trị được lưu trữ trong một biến sau khi nhấp vào nút. Bạn đang làm điều đó một cách chính xác ... Tại sao bạn cảm thấy như thế này là không chính xác? –
Không, tôi không cố gắng chuyển đổi đầu vào thành một số. Bản thân đầu vào là một số. Tôi đang tìm cách lưu số đó vào một biến số – crossemup