簡體   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