我已经创建了一个简单的信条(创建,审阅,编辑,删除,概述)汽车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