我已經創建了一個簡單的信條(創建,審閱,編輯,刪除,概述)汽車wpf應用程序瞭解有關c#並遇到問題。當添加或編輯項目到我的可觀察集合時,我想讓用戶能夠瀏覽計算機以獲取與汽車相關的圖片。我原本在後面的代碼與完成此如下:xaml綁定不按預期工作
namespace CarApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Open a browser window when the user clicks on the 'browse' button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Add_Browse_Button_Click(object sender, RoutedEventArgs e)
{
//send path to textbox
AddPicturePath.Text = this.Browse();
}
///// <summary>
///// Open a browser window when the user clicks on the 'browse' button
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
private void Edit_Browse_Button_Click(object sender, RoutedEventArgs e)
{
//send path to textbox
EditPicturePath.Text = this.Browse();
}
/// <summary>
/// Open browser window and return user selection
/// </summary>
/// <returns>filename</returns>
private string Browse()
{
//open browser window
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//search only for .png files
dlg.DefaultExt = ".png";
//show browser
dlg.ShowDialog();
return dlg.FileName;
}
}
}
這完美地工作,但後來我被要求後面(這似乎罰款是去除所有的代碼,因爲這純粹是一個UI元素,如果我告訴我錯了)。讓我感動的代碼放到一個ICommand:
namespace CarApp.Commands
{
public class BrowseCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
Car param = parameter as Car;
try
{
//open browser window
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//search only for .png files
dlg.DefaultExt = ".png";
//show browser
dlg.ShowDialog();
//send path to textbox
param.PicturePath = dlg.FileName;
}
catch (NullReferenceException)
{
Console.Write("Param is null in browse");
}
}
}
}
現在,當我運行應用程序,路徑沒有出現在文本框中顯示出來的時候,當我點擊「添加到列表」按鈕,該項目將被添加顯示正確的形象。看起來好像文本框沒有更新,即使我已經實現了通知。我錯過了明顯的東西嗎?下面是相關的XAML代碼:
<Button Width="75"
Height="23"
Margin="10,0,0,0"
HorizontalAlignment="Left"
Command="{Binding BrowseCommand}"
CommandParameter="{Binding NewCar}"
Content="Browse" />
和
<TextBox x:Name="AddPicturePath"
Width="200"
Height="23"
Margin="10,0,0,0"
HorizontalAlignment="Left"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Text="{Binding NewCar.PicturePath,
UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" />
假設您使用Visual Studio,輸出控制檯中是否有任何錯誤?另外,你有'DataContext'設置正確嗎? – GEEF
@VP輸出控制檯中沒有錯誤。我假設我的DataContext設置正確,因爲我所有的其他命令按預期工作,並使用代碼隱藏,瀏覽工程以及。 – Connor