2012-04-05 97 views
1

我在論壇中搜索了一個解決方案。有幾個類似的問題和解決方案,但我無法真正理解它們。請原諒我再次提問...:P在UserControl中暴露了DependencyProperty,但無法綁定

讓我解釋一下我的設置...我有一個UserControl,它是從主應用程序開發的一個單獨的dll。在這個相當複雜的UserControl中,我有幾個子控件。其中之一是圖像。我在UserControl代碼後面聲明瞭一個DependencyProperty來公開Image的Source屬性。

public static DependencyProperty MyImageSourceProperty = DependencyProperty.Register("MyImageSource", typeof(ImageSource), typeof(MyUserControl), new UIPropertyMetadata(null)); 

public ImageSource MyImageSource 
{ 
    get { return (ImageSource)GetValue(MyImageSourceProperty); } 
    set { SetValue(MyImageSourceProperty, value); } 
} 

然後在我的主要應用,我把用戶控件在我的主窗口和操縱它,因爲這樣...

<controls:MyUserControl Name="MyControl" MyImageSource={Binding MySource}/> 

MYSOURCE在我的主窗口的視圖模型聲明。

public string MySource 
    { 
     get { return this.mySource; } 
     set { if (value == mySource) 
       return; 
      this.mySource = value; 
      OnPropertyChanged("MySource"); 
      } 
    } 

基本上,該程序是應該起到這樣: 1)用戶點擊在主窗口的按鈕。 2)openFileDialog彈出,他選擇一個圖像文件加載。 3)一旦他確認選擇,圖像應加載在MyUserControl的圖像控件中。即更新MySource,這會觸發事件的整個波動,導致更新圖像的源屬性。

彙編無誤。但是當我試圖執行程序,並選擇我想要加載的圖像時,圖像根本不顯示...

希望有人能夠在這方面給我啓發。真的砰的一聲撞在牆上了幾個小時試圖找出什麼地方出了錯....感謝很多提前...

+0

你應該在Visual Studio控制檯中有綁定錯誤,它可以幫助你解決你的問題 – Jonas 2012-04-05 07:25:47

+0

已經指定窗體的類作爲窗體的數據源?否則:她應該如何控制哪個對象包含'MySource'屬性?例如,你可以在構造函數中做到這一點。 – 2012-04-05 07:25:59

+1

您不能將ImageSource直接綁定到字符串。 有關更多詳細信息,請參見[將圖像綁定到WPF中的字符串](http://stackoverflow.com/questions/2573912/binding-image-source-to-string-in-wpf) – DmitryG 2012-04-05 07:39:24

回答

1

以下行添加到構造函數:

this.DataContext = this; 

這告訴形式,它是它自己的數據上下文。否則,用戶控件不知道哪個對象「主辦」MySource屬性。

相關問題