绑定更新变量
本文关键字:变量 更新 绑定 | 更新日期: 2023-09-27 18:24:09
我有一个大问题,一直在努力解决。。。
所以我想做的是:-我用Codebehind文件将一个按钮添加到我的Wrapgrid中-此按钮应更改作为图像来源的变量
Datenbank database = new Datenbank();
Binding bind = new Binding("ValueGet");
bind.Source = database;
bind.Mode = BindingMode.OneWay;
System.Windows.Controls.Button champbtn = new System.Windows.Controls.Button();
champbtn.Name = "btnAhri";
champbtn.Width = 60;
champbtn.Height = 60;
champbtn.Margin = new Thickness(4);
champbtn.SetBinding(Button.CommandProperty, bind);
champbtn.ToolTip = "Ahri";
champbtn.Content = "Press me";
WrapGrid.Children.Add(champbtn);
这是有效的。我得到了我的按钮,它是可点击的。现在,正如你所看到的,我在我的另一个类"Datenbank"中添加了一些命令绑定,看起来像这样:
public class Datenbank : INotifyPropertyChanged
{
private string _Source;
public string ImgSource
{
get { return _Source; }
set
{
_Source = value;
NotifyPropertyChanged("ImgSource");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
public DelegateCommand ValueGet{ get; set; }
public Datenbank()
{
ValueGet = new DelegateCommand(Ahri);
}
private void Ahri(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("test");
ImgSource = "Ahri_Square_0.png";
}
}
这是我的DelegateCommand类:
public class DelegateCommand : ICommand
{
public delegate void SimpleEventHandler(object sender, EventArgs e);
private SimpleEventHandler _eventHandler;
public DelegateCommand(SimpleEventHandler eventHandler)
{
_eventHandler = eventHandler;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_eventHandler(this, new EventArgs());
}
}
正如你所看到的,生成的按钮应该更改"ImgSource"的字符串
这个变量绑定到我的xaml代码中的一个imagebox:
<Image Height="50" Name="image1" Stretch="Fill" Width="50" Source="{Binding ImgSource, Source={StaticResource database}}" />
这也可以。所以现在我的问题是,当我按下生成的按钮时,我的"测试"消息框会出现,但图像不会更改其来源,我真的不知道如何解决这个问题。
当我用与上面生成的按钮相同的命令手动添加按钮时,它工作得很好!
<Button Command="{Binding ValueGet,Source={StaticResource database}}">Press ME</Button>
它会立即更改图像源和图片,但不会与生成的图像一起出现,这很重要!
所以我希望任何人都能帮我解决这个问题,因为我找不到问题。
映像不是作为应用程序/程序集的资源生成的。试试看。
- 转到解决方案资源管理器
- 右键单击图像
- 选择属性
- 您将看到"构建操作"
生成操作值应为"Resource"。
我希望这能有所帮助。