[問題] WPF DataTemplate Binding Command Fail

看板C_Sharp作者 (呆呆要不要買降有)時間4年前 (2019/10/30 16:08), 4年前編輯推噓0(003)
留言3則, 1人參與, 4年前最新討論串1/1
問題是這樣的(已解決) 我有一個DataGrid希望透過DataBinding的方式去設定資料 但是在指定Column除了顯示資料外還要多一顆按鈕可以做其他事情 https://imgur.com/a/fGrnv7W 資料我有Binding到了但是按鈕沒有成功Binding到Command 看Code很煩所以我簡單描述一下我的ViewModel長怎樣 DataModel { UserId . . .其他欄位. ... } ViewModel { public ObservableCollection<DataModel> GridSource public Command ButtonClickCommand } 我在想是不是因為ItemSource只Binding到GridSource 他的DataTemplate裡的Button沒辦法從父層找到Command 所以我就在Command後面加了一段Code從最外層(window)去找要Binding的Command Command="{Binding ButtonChooseUserIdClick, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" 結果也是沒找到,想請教一下這個失敗的原因是什麼 ********************************************************************* 我自己找到解決方法了 Command="{Binding RelativeSource={ RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ButtonChooseUseridClick}" 加Path上去然後選DataContext裡對應的Command就可以了 思考的方向應該沒有錯,就是Button在DataGrid裡面 DataGrid因為Itemsource有Binding屬性了,所以Button沒有辦法找到他要的東西 就改從window去找(this.DataContext = ViewModel) 但因為沒有指定RelativeSource的Path要哪個屬性所以沒有Binding成功 ********************************************************************* Code大概長這樣 Xaml: <DataGrid ItemSource={Binding GridSource}> <DataGrid.Columns> <DataGridTemplateColumn Header="標題"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Stackpanel Oriented="Horizontal"> <TextBox Text={Binding UserId}/> <Button Content="." Command="{Binding ButtonCommand}"/> </...> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTextColumn> </DataGrid.Columns> </DataGrid> CodeBehind: public MainWindow() { init..(); MainViewModel mv = new MainViewModel(); this.DataComtext = mv; } ViewModel: public void ViewModel:INotifyPropertyChanged { public void OnpropertyChanged(string propertyName){....} private ObservableCollection<DataModel> _GridSource = new ...; public ObservableCollection<DataModel> GridSource { get{return _GridSource;} set{_GridSource = value;OnPropertyChanged("GridSource");} } public Command ButtonCommand{get;set;} public void ButtonCommandAction(){//do something..} //ViewModel建構子 public ViewModel() { ButtonCommand = new Command(ButtonCommandAction); } } --

09/05 19:33,
我國中都全校前10名
09/05 19:33

09/05 19:34,
全校有10個人
09/05 19:34

09/05 19:38,
其中5個缺席
09/05 19:38

09/05 19:39,
4個資源斑
09/05 19:39

09/05 19:56,
1個鄉民
09/05 19:56
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.75.101.50 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1572422939.A.D8F.html

10/30 16:24, 4年前 , 1F
最近我都用click直接call datacontext...
10/30 16:24, 1F
這個問題我只要願意用Click去做就可以秒解了....

10/30 16:28, 4年前 , 2F
我之前寫的<Button Command="{Binding DataContext.cmd
10/30 16:28, 2F

10/30 16:29, 4年前 , 3F
也是加上DataContext
10/30 16:29, 3F
※ 編輯: e23882 (211.75.101.50 臺灣), 11/14/2019 14:42:38
文章代碼(AID): #1TkKKRsF (C_Sharp)