TextBox.TextProperty 绑定 int
时间: 2023-12-10 13:40:40 浏览: 89
将 TextBox.TextProperty 绑定到 int 是不可能的,因为 TextBox.TextProperty 是一个字符串类型的依赖属性,而 int 是一个整数类型。你需要使用一个转换器来将字符串转换为整数,然后将其绑定到 int 类型的属性。可以使用 System.Windows.Data.Binding 类来实现数据绑定,并使用 System.Windows.Data.IValueConverter 接口来实现转换器。以下是一个示例转换器代码:
```csharp
public class StringToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string str)
{
if (int.TryParse(str, out int result))
{
return result;
}
}
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int intValue)
{
return intValue.ToString();
}
return "0";
}
}
```
在 XAML 中,你可以这样使用转换器:
```xml
<Window xmlns:local="clr-namespace:YourNamespace">
<Window.Resources>
<local:StringToIntConverter x:Key="StringToIntConverter" />
</Window.Resources>
<StackPanel>
<TextBox Text="{Binding MyIntProperty, Converter={StaticResource StringToIntConverter}}" />
</StackPanel>
</Window>
```
这里的 MyIntProperty 是一个 int 类型的属性,你可以将其绑定到 TextBox.TextProperty。使用转换器将字符串转换为整数,然后将其赋值给 MyIntProperty 属性。同时,当用户在 TextBox 中输入整数时,转换器还可以将其转换为字符串并更新到 TextBox 中。
阅读全文
相关推荐


















