In my application I'm using a ribbon control, on this ribbon is a button. When I click the button it should get the selected value from the datagrid in my view.
Now when I click the button the value it gets is always null
.
This is my code:
View1.xaml
<ScrollViewer Background="White" Grid.Row="1" Grid.Column="1" Margin="2" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Visible">
<DataGrid SelectionMode="Single" ItemsSource="{Binding Collection}" SelectedItem="{Binding Test, Mode=TwoWay}" AutoGenerateColumns="False" Name="stackpanelLocked" HorizontalAlignment="Left">
<DataGrid.Columns>
<DataGridTextColumn Header="RandomHeaderX" Binding="{Binding Path=X}"/>
<DataGridTextColumn Header="RandomHeaderY" Binding="{Binding Path=Y}"/>
</DataGrid.Columns>
</DataGrid>
</ScrollViewer>
Viewmodel
//get selected item value
string lastSelectedValue;
private Model _test;
public Model Test
{
get
{
return _test;
}
set
{
_test = value;
if(Test != null)
this.lastSelectedValue = string.Format("Variabele X: {0} Variabele Y: {1}", Test.X, Test.Y);
}
}
private ICommand _ClickCommand;
public ICommand ClickCommand
{
get
{
if (_ClickCommand == null)
_ClickCommand = new DelegateCommand(new Action(Execute),
new Func<bool>(CanExecute));
return _ClickCommand;
}
}
public bool CanExecute()
{
return true;
}
public void Execute()
{
if(lastSelectedValue != null)
Clipboard.SetText(lastSelectedValue);
}
Model
public int X { get; set; }
public int Y { get; set; }
public Model(int x, int y)
{
X = x;
Y = y;
}
Extra info:
Every time I click in the datagrid it will actually fill the string
lastSelectedValue
.
But when I click the button on the ribbon it will say that the lastSelectedValue
is null.
Collection stuff:
public List<DatabaseClass.coord> AllCoords { get; set; }
public ObservableCollection<Model> Collection { get; set; }
public ModuleARibbonTabModel()
{
Collection = new ObservableCollection<Model>();
GenerateDatas();
}
private void GenerateDatas()
{
using (var ctx = new DatabaseClass.TestDatabaseEntities1 ())
{
AllCoords = ctx.coord.ToList();
}
foreach(DatabaseClass.coord f in AllCoords)
{
Collection.Add(new Model(Convert.ToInt32(f.Een.ToString()), Convert.ToInt32(f.Twee.ToString())));
}
}
I managed to work around the problem.
I don't think this is a good fix but this is what I changed:
I changed the string lastSelectedValue
to a static string lastSelectedValue
This makes sure I can get the value.