我在usercontrol中使用了文本块,但是当我传递一些在textblock中查看的值时,我正在从其他表单向textblock发送值,但我需要将数字转换为文本。所以我在textblock中使用了转换器。但它不起作用
<TextBlock Height="21" Name="txtStatus" Width="65" Background="Bisque" TextAlignment="Center" Text="{Binding Path=hM1,Converter={StaticResource TextConvert},Mode=OneWay}"/>
转换器类
class TextConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if (value.ToString() == "1")
{
return value = "Good";
}
if (value.ToString() == "0")
{
return value = "NIL";
}
}
return value = "";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (string)value;
}
}
是吗?什么错了?
答案 0 :(得分:3)
好吧我想我知道问题是什么 - 看看我是否可以为你定义它:)
在你想要使用TextConvert的xaml文件中,为它定义Resource(除非你已经这样做了,然后我不知道为什么它不能正常工作)
<Grid.Resources>
<Shared:TextConvert x:Key="TextConvertKey" />
</Grid.Resources>
共享为xmlns ofcourse。
然后在文本框中使用它:
Text="{Binding Path=hM1,Converter={StaticResource TextConvertKey},Mode=OneWay}"/>
编辑:
如果在转换器类中设置断点,调试器是否会进入?????
编辑2:
我正在使用像这个伏都教
local:HealthTextConvert x:Key =“TextConvert”
这绝对是错误的。当转换器名称为TextConvert ???
时,如何将其称为HealthTextConvert应该是
local:TextConvert x:Key="whateverKeyNameYouWant"
和
文本框中的应该是
Text="{Binding Path=hM1,Converter={StaticResource whateverKeyNameYouWant},Mode=OneWay}"
答案 1 :(得分:1)
我可以立即看到您的转换器定义出现问题。
class TextConvert : IValueConverter
{
...
应该公开宣布能够将其用作资源。
public class TextConvert : IValueConverter
{
...
此外,做这件事并不是一件好事......
return value = "Good";
...
return value = "NIL";
它应该是(即使你离开它也没关系,只是糟糕的编程= P):
return "Good";
...
return "Nill";
答案 2 :(得分:0)
请尝试删除以下行中的Path
Text="{Binding **Path**=hM1,Converter={StaticResource TextConvert},Mode=OneWay}".
有时它没有Path
:)。
还要查看输出窗口(Alt + Cntl + O)...以查看问题所在。