I need to read the id from the label and write it to a global variable to render the content on a separate page. But since this label is generated by ItemControls, I don't know how to refer to it. How can you implement separate pages that are automatically generated based on what the user clicked on?
Model global
public class global
{
public static int userid;
public static string username;
public static int catid;
}
The markup of the page to navigate from
<ItemsControl Name="icCatList">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<materialDesign:Card Margin="10 0 10 10 " Cursor="Hand" materialDesign:ElevationAssist.Elevation="Dp3" MouseDoubleClick="Cat_Click">
<StackPanel Height="200" Width="200">
<Image Source="F:\C#\Historical Saratov\Historical Saratov\App_Logo.png"/>
<Label Content="{Binding ID}" Visibility="Hidden" Height="1" x:Name="Cat_Label"/>
<TextBlock
FontSize="18"
FontWeight="Medium"
Text="{Binding Cat_Name}"
/>
<TextBlock
FontSize="15"
FontWeight="Regular"
Text="{Binding Description}"
/>
</StackPanel>
</materialDesign:Card>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
An example of a request based on which I tried to make a new page
InitializeComponent();
DB db = new DB();
string query = $"SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}";
MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
db.openConnection();
MySqlDataReader myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
FN_Label.Content = myReader.GetString("FirstName");
LN_Label.Content = myReader.GetString("LastName");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
How do I try to read and find the data that I need to feed into the markup
List<CatModel> items = new List<CatModel>();
DB db = new DB();
db.openConnection();
MySqlCommand cmd = new MySqlCommand($"SELECT Cat_Name, Description FROM Category WHERE ID = {Cat_Label}", db.GetConnection());
using (var rd = cmd.ExecuteReader())
{
while (rd.Read())
{
items.Add(new CatModel() {Cat_Name = rd.GetString(0),Description = rd.GetString(1)});
}
}
icCatList.ItemsSource = items;
You could add an ItemContainerStyle with an EventSetter for e.g. the MouseLeftButtonUp
event. In the event handler, you can access the clicked item via the Content
property of the item container element (i.e. a ContentPresenter):
<ItemsControl Name="icCatList">
...
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<EventSetter Event="MouseLeftButtonUp"
Handler="OnItemMouseLeftButtonUp"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
The event handler:
private void OnItemMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var content = (ContentPresenter)sender;
var item = (CatModel)content.Content;
var id = item.ID;
Debug.WriteLine(id);
}