根据数据源放入文本框中的值更新绑定到数据源的文本框的内容
本文关键字:数据源 文本 绑定 更新 | 更新日期: 2023-09-27 17:54:37
我有一个文本框,它绑定到一个数据服务以获取其内容。目前,数据服务将在该文本框中输入1到9之间的数字。我需要做的是基于那个值将文本框的内容替换为一个字符串。例如,如果文本框的原始内容是"1",那么它将被替换为"1 -这里的示例文本"
下面是定义文本框的代码。
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding Category1}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="{Binding Category2}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="{Binding Category3}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
我想我可能会使用else if语句,但我不知道如何从if语句中引用文本块。
谢谢你的帮助
你需要给TextBlock命名,这样它就可以被后面的代码引用,这样就可以像下面的代码一样工作了
<TextBlock x:Name="tb1" Text="{Binding Category1}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextNormalStyle}"/>
if (tb1.Text == "something")
{
DoSomething();
}
else
{
DoSomethingElse();
}
您可以定义一个值转换器。例如:
public class IntToTextConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Do the conversion from int to Text
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Do the conversion from Text to int
}
}
<Window x:Class="MyNamespace.Window1"
...
xmlns:my="clr-namespace:MyNamespace"
...>
<Window.Resources>
<my:IntToTextConverter x:Key="converter" />
</Window.Resources>
<Grid>
<TextBox Text={Binding Category1, Converter={StaticResource converter}}/>
</Grid>
</Window>
这里有一篇关于值转换器的好文章