【问题标题】:Binding Update Variable绑定更新变量
【发布时间】:2012-03-04 12:25:13
【问题描述】:

我在那里遇到了一个大问题,并试图解决它这么久......

所以我尝试做的是: - 我使用 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);

这行得通。我得到了我的按钮和它的可点击性。 现在你可以看到我在我的另一个类“Datanbank”中添加了一些命令绑定,如下所示:

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 代码中的图像框:

<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>

它会立即更改图像源并显示图片,但不会与生成的图片一起出现,这很重要!

所以我希望任何人都可以帮助我解决这个问题,因为我找不到问题。

【问题讨论】:

    标签: c# wpf variables binding runtime


    【解决方案1】:

    图像不是作为应用程序/程序集的资源构建的。 试试看吧。

    • 转到解决方案资源管理器。
    • 右键单击图像
    • 选择属性
    • 您将看到“构建操作”

    构建操作值应为“资源”。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2013-06-09
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多