【问题标题】:Binding to Code Behind will not work绑定到后面的代码将不起作用
【发布时间】:2013-01-09 15:52:39
【问题描述】:

我有一个按钮,它调用一个方法,该方法用图像路径填充List<string>。每次调用此方法以显示所有生成的图像时,我都会尝试更新 Windows 8 应用程序。 目前它不会显示任何内容,尽管只是将图像路径硬编码到List<string>

我显示图像的 XAML 代码是:

        <ItemsControl ItemsSource="{Binding Path=test}" Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="5"
      HorizontalContentAlignment="Stretch">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

在 Xaml.cs 中:

public sealed partial class MainPage : TestApp.Common.LayoutAwarePage
{

    public List<string> test = new List<string>();
    public MainPage()
    {
        test.Add("C:\\Users\\user\\Pictures\\image.jpg");
        this.InitializeComponent();
    }
}

我做错了什么/需要在这里更改?非常感谢:)。

【问题讨论】:

    标签: c# windows xaml windows-8


    【解决方案1】:

    您需要设置 MainPage 的 DataContext。将它放在您的 MainPage xaml 中。

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    编辑:您需要在代码隐藏中拥有一个属性,而不是字段:

    public List<string> test {get; set;}
    public MainPage()
    {
        test = new List<string>();
        test.Add("C:\\Users\\user\\Pictures\\image.jpg");
        this.InitializeComponent();
    }
    

    【讨论】:

    • 非常感谢您的回答...我已经添加了这个,但图像仍然没有出现:(
    • 您的输出窗口中是否出现任何绑定错误?现在 ItemsControl 中是否至少显示了项目,但没有图像?
    • 很遗憾,什么也没有出现。这是从“输出”窗口产生的错误消息(非常感谢您告诉我也检查这个,我根本没有意识到绑定问题已输出!)错误:BindingExpression 路径错误:在“TestApp.主页'。 BindingExpression: Path='test' DataItem='TestApp.MainPage';目标元素是'Windows.UI.Xaml.Controls.ItemsControl'(名称='null');目标属性是“ItemsSource”(类型“对象”)
    • 哦...那是因为您的代码后面有一个公共字段...不是公共财产。我将编辑我的答案以使其清楚。
    • 非常感谢。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2018-05-08
    • 2018-10-30
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多