怎样引用ItemsControl中的Label元素以从中读取数据?

huangapple go评论65阅读模式
英文:

How to refer to the Label element in the ItemsControl to read data from it?

问题

我需要从标签中读取ID并将其写入一个全局变量,以便在单独的页面上呈现内容。但由于此标签是由ItemControls生成的,我不知道如何引用它。如何实现根据用户点击的内容自动生成单独的页面?

全局模型

public class global
{
    public static int userid;
    public static string username;
    public static int catid;
}

要导航到的页面的标记

<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>

我尝试根据以下示例创建新页面的请求

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;
}

我尝试读取并找到需要输入到标记中的数据

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;
英文:

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

 &lt;ItemsControl Name=&quot;icCatList&quot;&gt;
                           &lt;ItemsControl.ItemsPanel&gt;
                               &lt;ItemsPanelTemplate&gt;
                                   &lt;StackPanel Orientation=&quot;Horizontal&quot;/&gt;
                               &lt;/ItemsPanelTemplate&gt;
                           &lt;/ItemsControl.ItemsPanel&gt;
                           &lt;ItemsControl.ItemTemplate&gt;
                               &lt;DataTemplate&gt;
                                   &lt;materialDesign:Card Margin=&quot;10 0 10 10 &quot; Cursor=&quot;Hand&quot; materialDesign:ElevationAssist.Elevation=&quot;Dp3&quot; MouseDoubleClick=&quot;Cat_Click&quot;&gt;
                                       &lt;StackPanel Height=&quot;200&quot; Width=&quot;200&quot;&gt; 
                                           &lt;Image Source=&quot;F:\C#\Historical Saratov\Historical Saratov\App_Logo.png&quot;/&gt;
                                           &lt;Label Content=&quot;{Binding ID}&quot; Visibility=&quot;Hidden&quot; Height=&quot;1&quot; x:Name=&quot;Cat_Label&quot;/&gt;
                                           &lt;TextBlock
                                               FontSize=&quot;18&quot;
                                               FontWeight=&quot;Medium&quot;
                                               Text=&quot;{Binding Cat_Name}&quot;
                                           /&gt;
                                           &lt;TextBlock
                                               FontSize=&quot;15&quot;
                                               FontWeight=&quot;Regular&quot;
                                               Text=&quot;{Binding Description}&quot;
                                           /&gt;
                                       &lt;/StackPanel&gt;
                                   &lt;/materialDesign:Card&gt;
                               &lt;/DataTemplate&gt;
                           &lt;/ItemsControl.ItemTemplate&gt;
                       &lt;/ItemsControl&gt;

An example of a request based on which I tried to make a new page

InitializeComponent();
            DB db = new DB();

            string query = $&quot;SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}&quot;;
            MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
            db.openConnection();
            MySqlDataReader myReader = cmd.ExecuteReader();

            try
            {
                while (myReader.Read())
                {
                    FN_Label.Content = myReader.GetString(&quot;FirstName&quot;);
                    LN_Label.Content = myReader.GetString(&quot;LastName&quot;);
                }
            }
            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&lt;CatModel&gt; items = new List&lt;CatModel&gt;();
            DB db = new DB();
            db.openConnection();
            MySqlCommand cmd = new MySqlCommand($&quot;SELECT Cat_Name, Description FROM Category WHERE ID = {Cat_Label}&quot;, 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;

答案1

得分: 0

常见的做法是使用 Model-View-ViewModel(mvvm)模式。通过这种方法,您将 ItemsSource 绑定到 viewModel 文件中的 ObservableCollection,其中包含所有项目。

要处理选择,首先需要使用支持选择的控件,例如 listview。然后,您可以绑定其中一个 Selected 属性,比如 SelectedIndex。从那里,只需简单地查找列表中的相同对象。完成后,您还有机会以任何需要的方式更新模型。

英文:

A common approach is to use the Model-View-ViewModel (mvvm) pattern. With this approach you bind the ItemsSource to an ObservableCollection in the viewModel file with all your items.

To handle selection you first need to use a control that support selection, for example a listview. You can then bind one of the Selected-properties, like SelectedIndex. From there it is a simple task of looking up the same object from the list. When this is done you also have the opportunity to update the model in any way you need.

答案2

得分: 0

你可以添加一个具有MouseLeftButtonUp事件的ItemContainerStyle,例如使用EventSetter。在事件处理程序中,您可以通过项目容器元素(即ContentPresenter)的Content属性访问单击的项目:

<ItemsControl Name="icCatList">
    ...
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <EventSetter Event="MouseLeftButtonUp"
                         Handler="OnItemMouseLeftButtonUp"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

事件处理程序:

private void OnItemMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    var content = (ContentPresenter)sender;
    var item = (CatModel)content.Content;
    var id = item.ID;
    Debug.WriteLine(id);
}
英文:

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):

&lt;ItemsControl Name=&quot;icCatList&quot;&gt;
    ...
    &lt;ItemsControl.ItemContainerStyle&gt;
        &lt;Style TargetType=&quot;ContentPresenter&quot;&gt;
            &lt;EventSetter Event=&quot;MouseLeftButtonUp&quot;
                         Handler=&quot;OnItemMouseLeftButtonUp&quot;/&gt;
        &lt;/Style&gt;
    &lt;/ItemsControl.ItemContainerStyle&gt;
&lt;/ItemsControl&gt;

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);
}

答案3

得分: -1

在设置MouseDoubleClick事件的那一行,当您双击特定的MaterialCard“Cat_Click”时,将调用以下函数:

在您的代码后台中定义以下函数:

private void Cat_Click(object sender, EventArgs e) {
    var catId = sender.ID;
    DB db = new DB();
    db.openConnection();
    MySqlCommand cmd = new MySqlCommand($"SELECT Cat_Name, Description FROM Category WHERE ID = {catId}", db.GetConnection());
    using (var rd = cmd.ExecuteReader()) {
        while (rd.Read()) {
            items.Add(new CatModel() { Cat_Name = rd.GetString(0), Description = rd.GetString(1) });
        }
    }
}
英文:

In that line where you set the MouseDoubleClick Event which will be called when you double click on the specific MaterialCard "Cat_Click"

Just define in your Code Behind the following function

private void Cat_Click(object sender, EventArgs e){

var catId = sender.ID;
            DB db = new DB();
            db.openConnection();
            MySqlCommand cmd = new MySqlCommand($&quot;SELECT Cat_Name, Description FROM Category WHERE ID = {catId}&quot;, db.GetConnection());
            using (var rd = cmd.ExecuteReader())
            {
                while (rd.Read())
                {
                    items.Add(new CatModel() {Cat_Name = rd.GetString(0),Description = rd.GetString(1)});
                }
            }
}

huangapple
  • 本文由 发表于 2023年3月3日 22:21:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定