[英]xaml binding not working as expected
我為汽車創建了一個簡單的credo(創建,查看,編輯,刪除,概述)wpf應用程序,以了解c#並遇到問題。 在向我的可觀察集合中添加或編輯項目時,我希望允許用戶能夠瀏覽計算機以查找與汽車關聯的圖片。 我最初是通過以下代碼在代碼中完成此操作的:
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");
}
}
}
}
現在,當我運行該應用程序時,該路徑不會顯示在文本框中,當我單擊“添加到列表”按鈕時,將添加顯示正確圖像的項目。 即使我實現了INotification,文本框似乎也沒有更新。 我是否缺少明顯的東西? 這與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" />
如果我理解正確,則說明您綁定到NewCar.PicturePath,但只有NewCar在更改。 當您通知屬性更改時,我猜您只通知NewCar對象正在更改(而不是PicturePath)。 嘗試這個; 在NewCar設置器中,設置_NewCar =值后,還要更新_NewCar.PicturePath並假設PicturePath也可以正確通知,它應該正確更新,並且還可以使您對綁定的工作方式有所了解...希望這會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.