0

コード ビハインドでは、ウィンドウの背景のイメージパスを設定します。xaml でこの値を取得し、それを使用して背景画像を設定する方法はありますか

4

2 に答える 2

2

最良の場合、コード ビハインドは空であるか、InitializeComponent だけが存在します。

したがって、これを達成する方法を強調し、将来の変更が非常に簡単になるようにします!

Window の DataContext を簡単に設定できます (コード ビハインドなど)。

この DataContext (このパスが変更されたときに INotifyPropertyChanged を実装する必要があります) から、必要なものに簡単にバインドできます。

以下に小さな例を示します。

// ViewModel class containing ImagePath

public class WindowBackgroundViewModel : INotifyPropertyChanged
{
    public string ImagePath { get; set; }
}


// in Codebehind
public WindowBackgroundViewModel ViewModel { get; set; }

// in Constructor
public myWindow()
{
    this.ViewModel = new WindowBackgroundViewModel();
    this.ViewModel.ImagePath = @"C:\myBackground.png";

    this.DataContext = this.ViewModel;
}


// in XAML
<...  ImageBackground="{Binding Path=ImagePath}"
于 2012-06-28T07:10:18.840 に答える
2

私は背景画像を表示していませんが、それでも次のバインディングはあなたの場合に有効なはずです:

XAML

<TextBox DataContext="{Binding RelativeSource={RelativeSource AncestorLevel=1,AncestorType=Window}}" 
 Text="{Binding MyProperty}" Width="200" Height="50"/>

C#

public partial class MainWindow : Window
    {
        public string MyProperty { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            MyProperty = "Sample";
        }
    }

これがあなたを助けることを願っています!

于 2012-06-28T07:07:57.730 に答える