元素在代码后面实例化时的绑定

时间:2013-05-07 14:45:47

标签: wpf data-binding

我有两个需要绑定的属性。一个是Value,它是UserControl的属性,第二个是来自image元素的属性。图像元素在Window中。 Window是在后面的代码(UserControl)中进行的。

我需要添加什么才能在图像src和属性Value之间实现正确绑定。代码如下所示。

<UserControl x:Class="nnnn">

<UserControl.Resources>
    <propSheet:BitmapConverter x:Key="bitmapConverter" />

    <Window x:Key="imagePopup"
            Width="640"
            Height="480">
        <Grid Background="LightGray">
            <Image Grid.Row="0" Source="{Binding Path=Value, Converter={StaticResource bitmapConverter}}" />

            <TextBlock Text="{Binding Path=Value}"></TextBlock>

            <Button Grid.Row="1"
                    Width="25"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Bottom"
                    Click="OpenFile_Click">
                ...
            </Button>
        </Grid>
    </Window>

</UserControl.Resources>

<Grid>
    <Button Click="ViewImage_Click">View Image</Button>

</Grid>

1 个答案:

答案 0 :(得分:1)

在显示之前,您必须将Window的DataContext属性设置为UserControl实例:

private void ViewImage_Click(object sender, RoutedEventArgs e)
{
    var window = Resources["imagePopup"] as Window;
    window.DataContext = this; // the UserControl
    window.Show();
}