Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 可以在鼠标单击事件中读取我的类,但可以';我不能修改它,为什么?_C#_Wpf_User Interface_Binding - Fatal编程技术网

C# 可以在鼠标单击事件中读取我的类,但可以';我不能修改它,为什么?

C# 可以在鼠标单击事件中读取我的类,但可以';我不能修改它,为什么?,c#,wpf,user-interface,binding,C#,Wpf,User Interface,Binding,我有一些问题,我只能在Mainwindow()方法中更新gui。并且无法真正理解为什么在事件中更改gui不起作用。我还使用绑定和viewmodel类 所以当我走出主窗口时,我的绑定似乎停止工作了 有什么想法吗 谢谢 public partial class MainWindow : Window { public ObservableCollection<ChessPiece> ItemX { get; set; } public MainWindow()

我有一些问题,我只能在Mainwindow()方法中更新gui。并且无法真正理解为什么在事件中更改gui不起作用。我还使用绑定和viewmodel类

所以当我走出主窗口时,我的绑定似乎停止工作了

有什么想法吗

谢谢

public partial class MainWindow : Window
{


    public ObservableCollection<ChessPiece> ItemX { get; set; }

    public MainWindow()
    {
       ItemX = new ObservableCollection<Chess>();

       InitializeComponent();
       DataContext = ItemX ;
       ItemX.Add(new Chess() { PosX = 0, PosY = 0, Type_ = Piece.Farmer, Player_ = PiecePlayer.Black });
       ItemX.Add(new Chess() { PosX = 0, PosY = 1, Type_ = Piece.Farmer, Player_ = Player.Black });


  ItemX.ElementAt(1).PosX = 5; //This works perfect, my GUI changes! 
}      

 public void ChessBoardClick(object sender, MouseButtonEventArgs e)
    {
       ItemX.ElementAt(0).PosX = 3; //Wont work, but the values inside ItemX changes. 


    }
公共部分类主窗口:窗口
{
公共可观测集合项x{get;set;}
公共主窗口()
{
ItemX=新的ObservableCollection();
初始化组件();
DataContext=ItemX;
Add(new Chess(){PosX=0,PosY=0,键入=Piece.Farmer,Player=PiecePlayer.Black});
Add(new Chess(){PosX=0,PosY=1,键入=Piece.Farmer,Player=Player.Black});
ItemX.ElementAt(1.PosX=5;//这很好用,我的GUI改变了!
}      
公共无效棋盘单击(对象发送器,鼠标按钮ventargs e)
{
ItemX.ElementAt(0.PosX=3;//不起作用,但ItemX中的值会更改。
}

当前,您的GUI没有太大的变化,只是从正确的开始…您没有
MainWindow
方法,您有一个
MainWindow
构造函数。只有在该构造函数完成后,UI才会完成更新,此时
PosX
已经是5了

要使UI对属性更改做出反应,需要实现
Chess
类,以便在更改
PosX
属性时触发事件

作为旁注,使用集合的索引器比使用
ElementAt
方法更为惯用,例如

ItemX[0].PosX = 3;

你说我的GUI发生了变化,但GUI在哪里?它绑定到什么?类是否正确实现了
INotifyPropertyChanged
?非常感谢,回答很好!我实际上在我的Chess类中添加了InotifyPropertyChange。我假设是propertychange一直在更新我的ui,而不是构造函数,所以我我想它正在工作。现在再次检查并注意到我有一些拼写错误,它现在工作了!再次感谢!:)也感谢您纠正我的错误假设以及ItemX[0]!