Reputation: 457
I want to bind IsEnable property of button to variable. Button is added inside data grid. Data Grid is located inside user control. Below code is not working.
<DataGridTemplateColumn Header="Start" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="Start_Button"
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Path=DataContext}"
IsEnabled="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}},Path=IsStartButtonEnable}"
Command="{Binding StartCommand}">START
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Model contains-(ServerModel.cs)
private bool _isStartButtonEnable = false;
public bool IsStartButtonEnable
{
get
{
return _isStartButtonEnable;
}
set
{
_isStartButtonEnable = value;
this.OnPropertyChanged("IsStartButtonEnable");
}
}
View Model(ServerViewModel.cs) Contains -
public static ObservableCollection<ServerModel> DataGridServerList { get; set; }
UserControl (ServerUserControl.cs) contains -
this.DataContext = new ServerViewModel();
Requirements - UserControl contains 3 buttons-Create, Start and Stop. User clicks on Create Button. If Create commnd gets success, then Start button gets enabled.Then user will click on Start button. If start commnd gets executed successfully, then Stop button gets enabled and so on.
Upvotes: 1
Views: 1062
Reputation: 2620
<DataGridTemplateColumn Header="Start" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="Start_Button"
IsEnabled="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Path=DataContext.IsStartButtonEnable}"
Command="{Binding StartCommand}">START
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
I am using the DataContext of the UserControl directly and not that of the DataGrid. In your case, indeed, the DataContext of the Button will be set to each item in the DataGrid. In order to access the property on your UserControl you need this change. Further more, you don't need to set the DataContext again so i removed that line.
You have two possibilities in my opinion. Either set the flag in the ViewModel and will be accessible by all Buttons through the Relative Source syntax or if you have it in the Model, you will have a flag for each row in the DataGrid. In either case you have the response:
If it is in the Model, set the DataGrid ItemsSource to your ObservableCollection and use
IsEnabled = {Binding IsStartButtonEnable }
2.If it is in the ViewModel, use
IsEnabled="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Path=DataContext.IsStartButtonEnable}"
I don't see other option but if you want it available for all Buttons in the DataGrid you have to set it in the ViewModel.
Upvotes: 2