我想結合的圖像源,事情是: 我有一個FileSystemWatcher的文件夾 - 每一個新的圖像文件被添加到該文件夾的時間 - 我得到的完整路徑該圖像並希望將其綁定到圖像控件的來源。 因此,每次將新的TIFF文件添加到文件夾時,圖像將在GUI中自動更改。如何綁定圖片來源
這是我做了什麼:
XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="414,159,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<Image x:Name="img1" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" RenderTransformOrigin="1.604,1.161" Source="{Binding ButtonImage}" />
</Grid>
</Window>
MainWindow.xaml.cs
private ImageSource b;
public ImageSource ButtonImage
{
get { return b; }
set
{
b = value;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
ButtonImage = new BitmapImage(new Uri(@"C:\Users\x\Desktop\1.tif"));
watch();
}
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\x\Desktop\ti";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
watcher.Filter = "*.tif";
}
private void OnChanged(object source, FileSystemEventArgs e)
{
ButtonImage = new BitmapImage(new Uri(e.FullPath));
}
_「我得到的圖像的完整路徑和要綁定的是圖像控件的來源」 _ - 那麼你爲什麼不能?您應該擁有一個視圖模型,將該路徑的屬性作爲源綁定到目標'Source'屬性。假設你已經正確地實現了你的視圖模型(你沒有,在上面的例子中),更新源屬性將自動更新目標屬性。 –
沒有好的[mcve],就不可能知道什麼是錯的。但是你所展示的代碼並沒有實現'INotifyPropertyChanged''(參見標記爲重複)並且不設置'DataContext'。另見https://stackoverflow.com/questions/2036518/learning-wpf-and-mvvm,https://stackoverflow.com/questions/997650/i-have-some-questions-about-mvvm-pattern,https: //stackoverflow.com/questions/1405739/mvvm-tutorial-from-start-to-finish,https://stackoverflow.com/questions/7063902/better-way-to-trigger-onpropertychanged,... –
.. 。https://stackoverflow.com/questions/772214/in-mvvm-should-the-viewmodel-or-model-implement-inotifypropertychanged,https://stackoverflow.com/questions/3130491/how-to-avoid-implementing -inotifypropertychanged-手動,https://stackoverflow.com/questions/488587/whats-the-best-way-to-call-inotifypropertychangeds-propertychanged-event,https://stackoverflow.com/questions/857820/big-smart -viewmodels啞意見,和任何模型最最好的MVVM的方法,並https://stackoverflow.com/questions/6789236/how-does-wpf-inotifypropertychanged-work –