繁体   English   中英

无法在代码后面更改图像源

[英]Can't change Image source in code behind

我正在尝试在后面的代码中更改Image.Source 当单击按钮时, Image.Source将在后面的代码中修改,并且应该在Windows中显示图像。 不幸的是,它似乎不起作用。 谁能告诉我问题出在哪里? 谢谢。

这是我的代码:

XML

`<Grid Margin="0,0,-234,0">
        <Image Source="{Binding SourceName, Mode=TwoWay}" 
        Height="100" Width="100" Margin="201,69,661,151"/>
        <Button Margin="201,215,644,39" Click="Button_Click">show image</Button>
 </Grid>`

C#部分:

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        Uri uri = new Uri(@"C:\localFTP\thisImage.jpg", UriKind.Absolute);

        BitmapImage i = new BitmapImage();
        i.BeginInit();
        i.UriSource = uri;
        i.EndInit();


        SourceName = i;
    }


    private ImageSource _sourceName;

    public ImageSource SourceName
    {
        get
        {
            return _sourceName;
        }
        set
        {
            _sourceName = value;
            OnPropertyChanged("SourceName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

您似乎在任何地方都没有设置绑定的来源。

因此,您可以设置MainWindow的DataContext,例如在类似

public MainWindow()
{
    InitializeComponent();   
    DataContext = this;
}

或者您可以显式指定绑定源,例如通过设置其RelativeSource:

<Image Source="{Binding SourceName,
                RelativeSource={RelativeSource AncestorType=Window}}"/>

请注意, SourceName对于ImageSource类型的属性似乎是一个奇怪的名称。 最好将其命名为SourceImageSource

还可能需要注意的是,创建BitmapImage实际上需要的代码比问题中显示的要少:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var uri = new Uri(@"C:\localFTP\thisImage.jpg");
    SourceName = new BitmapImage(uri);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM