c# - 绑定(bind)到代码隐藏将不起作用

标签 c# windows xaml windows-8

我有一个按钮,它调用一个填充 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();
    }
}

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

最佳答案

您需要设置 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();
}

关于c# - 绑定(bind)到代码隐藏将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241065/

相关文章:

windows - 在 Windows 8 上安装 AppFabric

c# - 如何以编程方式在 Windows 8.1 中 ScrollView ?

c# - 如何在winform中移动动态添加的图形线

c# - 如何在 C# 中使用 XPath 检索最后一个节点?

c++ - 在 C++ 中将 UTF8 字符串转换为 UTF16 字符串

c# - 为什么 WPF 设计器无法加载

wpf - 鼠标悬停在父元素上时触发

c# - 在哪里存储桌面应用程序的用户数据?

c# - 将后台 worker 更新为异步等待

Windows 还原点 - RestorePointType 的含义