【问题标题】:How to do Binding Stackpanel and stringFormat?如何绑定 Stackpanel 和 stringFormat?
【发布时间】:2011-06-10 22:15:50
【问题描述】:

我有一些堆栈面板,在他下面有 4 个需要显示一些信息的文本块。 我对堆栈面板( DataContext )进行了一些绑定,并将文本块与绑定到堆栈面板的对象所保存的信息绑定。

我编写了代码 + xaml,但没有任何效果。 我得到关于格式错误的异常。

代码:

 public partial class SomeDemoClass: UserControl
{
    classObjDemo c1;

    public SomeDemoClass()
    {
        InitializeComponent();

        c1 = new classObjDemo()
        {
              val1 = 5.5,
              val2 = 2.3
        }; 
    }
 }

xaml(匹配类“SomeDemoClass”)

   <StackPanel x:Name="LayoutRoot" DataContext="{Binding ElementName=SomeDemoClass, Path=c1">

      <TextBlock Text="{Binding val1, StringFormat={0:F} }" />
      <TextBlock Text="{Binding val2, StringFormat={0:F} }" />


   </StackPanael>

【问题讨论】:

    标签: wpf silverlight


    【解决方案1】:

    您将 x:Name="SomeDemoClass" 放在 xaml 的 op 中,并使 c1 成为公共属性,而不是它可以工作的字段。 ElementName 按名称引用 xaml 中的元素,并且绑定仅适用于属性和依赖项属性。

    <UserControl x:Name="SomeDemoClass" ...
    
    public classObjDemo c1 { get; set; }
    

    同时检查您的 Visual Studio 输出窗口是否存在绑定错误。

    编辑

    还要确保 classObjDemo 的 v1 和 v2 是公共属性

    然后在你的 xaml 中转义 {见http://elegantcode.com/2009/04/07/wpf-stringformat-in-xaml-with-the-stringformat-attribute/

    <TextBlock Text="{Binding val2, StringFormat={}{0:F} }" />
    

    【讨论】:

    • 看不懂你写的东西。
    • 我将此添加到我的代码中 - 将字段更改为属性 - 没有任何事情发生。还是不行。
    • 还要确保 classObjDemo 的 val1 和 val2 是属性,而不是字段
    • 是的,它们是属性。我得到的错误是“'System.Windows.Data.Binding'类型的对象无法转换为'System.String'类型。”
    • 我还检查了 Text="{Binding val1, StringFormat=\{0:F\}} 的选项,但仍然无法正常工作
    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2016-04-15
    • 2021-12-17
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多