簡體   English   中英

窗口中用戶控件的C#WPF調用方法

[英]C# WPF call method from user control in window

我有一個大問題。...我有一個MainWindow.xaml。 這個xaml分為不同的列和行。 在左側,我有不同的按鈕。 在右側,我有所謂的內容網格。 在此內容網格中,我通過按一個按鈕打開我的不同用戶控件。

在這些用戶控件之一中,我請求從A到B的路線。如果明確標識了這些點,則該路線將顯示在輸入屏幕下方的列表框中。

但是,如果不能正確識別這兩個點之一,我將打開一個帶有兩個組合框的新窗口,您必須在其中指定並選擇輸入。 在選擇起點和終點之后。 按下“確定”按鈕應關閉該窗口,並在用戶控件的列表框中顯示該路線。...但不是...

我的英語不好,我希望您能通過發布代碼來幫助我。

用戶控件文件的代碼如下:

RoutenplanungSelection rps = new RoutenplanungSelection();
public void checkStationsnamenSindEindeutig(string von, string nach, string datum, string zeit, bool abfahrt)
    {

        WebClient wc = new WebClient();
        wc.Encoding = Encoding.UTF8;
        string data = wc.DownloadString(....url);
        var xe = XElement.Parse(data);

        var CountOrigins = from a in xe.Descendants("itdOdv")
                           where a.Attribute("usage").Value == "origin"
                           select a.Element("itdOdvName").Elements("odvNameElem").Count();

        var CountDestinations = from a in xe.Descendants("itdOdv")
                                where a.Attribute("usage").Value == "destination"
                                select a.Element("itdOdvName").Elements("odvNameElem").Count();



        int countorigins = 0;
        foreach (var c in CountOrigins)
            countorigins = Convert.ToInt32(c);

        int countdestinations = 0;
        foreach (var c in CountDestinations)
            countdestinations = Convert.ToInt32(c);

        if (countorigins == 1 && countdestinations == 1)
        {
            downloadEindeutigenXml(von, nach, datum, zeit, abfahrt);
        }



        if (countorigins > 1 || countdestinations > 1)
        {
            var getAllOrigins = from a in xe.Descendants("itdOdv")
                                where a.Attribute("usage").Value == "origin"
                                select a;

            var getAllDestinations = from a in xe.Descendants("itdOdv")
                                where a.Attribute("usage").Value == "destination"
                                select a;


            foreach(var r in getAllOrigins)
                rps.uebergebeXmlOrigins(r);

            foreach (var r in getAllDestinations)
                rps.uebergebeXmlDestination(r);

            rps.uebergebeAllgemeineInfos(datum, zeit, abfahrt);
            rps.Show();


        }

    }



    public async void downloadEindeutigenXml(string von, string nach, string datum, string zeit, bool abfahrt)
    {


        WebClient wc = new WebClient();
        wc.Encoding = Encoding.UTF8;
        if(abfahrt) 
        {
            this.mw = (MainWindow)Application.Current.MainWindow;
            mw.progress.IsIndeterminate = false;
            mw.progress.IsIndeterminate = true;
            formatEindeutigeData(XElement.Parse(await wc.DownloadStringTaskAsync(
            "....url")));
            mw.progress.IsIndeterminate = false;
        }
        else 
        {
            this.mw = (MainWindow)Application.Current.MainWindow;
            mw.progress.IsIndeterminate = false;
            mw.progress.IsIndeterminate = true;
            formatEindeutigeData(XElement.Parse(await wc.DownloadStringTaskAsync(
            "....url")));
            mw.progress.IsIndeterminate = false;
        }
    }

    private string addZeros(string number)
    {
        if (number.Length < 2)
            return number.Insert(0, "0");
        else
            return number;

    }
    private void formatEindeutigeData(XElement xml)
    {

        box.Items.Clear();
        var checkConnections = (from a in xml.Descendants("itdMessage")
                               where a.Attribute("code").Value == "-4000"
                               select a).Count();



        var checkDateValid = (from a in xml.Descendants("itdMessage")
                              where a.Attribute("code").Value == "-4001"
                              select a).Count();

        if (checkConnections == 1)
        {
            TextBlock nothing = new TextBlock();
            nothing.TextAlignment = TextAlignment.Center;
            nothing.HorizontalAlignment = HorizontalAlignment.Center;
            nothing.FontSize = 18;
            nothing.Text = "\n\n\nLeider gibt es keine Verbindung zu Ihrem gewünschten Ziel! :-(";
            box.Items.Add(nothing);
        }

        if (checkDateValid == 1)
        {
            TextBlock nothing = new TextBlock();
            nothing.TextAlignment = TextAlignment.Center;
            nothing.HorizontalAlignment = HorizontalAlignment.Center;
            nothing.FontSize = 18;
            nothing.Text = "\n\n\nDatum außerhalb der Fahrplanperiode! :-(";
            box.Items.Add(nothing);
        } 




        var result = (from a in xml.Descendants("itdRouteList").Elements("itdRoute")
                     select new
                     {
                         partialRoute = from b in a.Descendants("itdPartialRouteList").Elements("itdPartialRoute")
                                        select new 
                                        {
                                            von = from c in b.Elements("itdPoint")
                                                  where c.Attribute("usage").Value == "departure"
                                                  select new 
                                                  {
                                                      station = c.Attribute("name").Value,
                                                      abfahrtdatum_jahr = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("year").Value,
                                                      abfahrtdatum_monat = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("month").Value,
                                                      abfahrtdatum_tag = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("day").Value,
                                                      abfahrtdatum_stunde = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("hour").Value),
                                                      abfahrtdatum_minute = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("minute").Value)
                                                  },
                                            nach = from c in b.Elements("itdPoint")
                                                   where c.Attribute("usage").Value == "arrival"
                                                   select new
                                                   {
                                                       station = c.Attribute("name").Value,
                                                       ankuftdatum_jahr = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("year").Value,
                                                       ankuftdatum_monat = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("month").Value,
                                                       ankuftdatum_tag = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("day").Value,
                                                       ankuftdatum_stunde = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("hour").Value),
                                                       ankuftdatum_minute = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("minute").Value)
                                                   },
                                            fahrmittel = from c in b.Elements("itdMeansOfTransport")
                                                         select new 
                                                         {
                                                             name_plus_linie = c.Attribute("name").Value,
                                                             linie = c.Attribute("shortname").Value,
                                                             symbol = c.Attribute("symbol").Value,
                                                             richtung = c.Attribute("destination").Value
                                                         }

                                        },
                            fahrzeit = a.Element("seqRoutes").Element("seqRoute").Attribute("publicDuration").Value

                     }).ToList();


        foreach (var r in result)
        {

            foreach (var q in r.partialRoute)
            {
                foreach (var s in q.von)
                {
                    foreach (var t in q.nach)
                    {
                        foreach (var a in q.fahrmittel)
                        {
                            //MessageBox.Show("von: " + s.ToString() + " nach: " + t.ToString() + " mittels " + a.name_plus_linie + " richtung " + a.richtung + "fahrzeit: " + r.fahrzeit);

                            TextBlock tb_name_linie_richtung = new TextBlock();
                            tb_name_linie_richtung.FontSize = 18;
                            if (a.name_plus_linie != "" && a.richtung != "")
                                tb_name_linie_richtung.Text = a.name_plus_linie + ", Richtung " + a.richtung;
                            else
                                tb_name_linie_richtung.Text = "Fußweg";
                            box.Items.Add(tb_name_linie_richtung);

                        }
                        TextBlock uhrzeit_von = new TextBlock();
                        uhrzeit_von.Text = s.abfahrtdatum_stunde + ":" + s.abfahrtdatum_minute + "   " + s.station;
                        box.Items.Add(uhrzeit_von);

                        TextBlock uhrzeit_nach = new TextBlock();
                        uhrzeit_nach.Text = t.ankuftdatum_stunde + ":" + t.ankuftdatum_minute + "   " + t.station;
                        box.Items.Add(uhrzeit_nach);

                    }

                }

            }
            box.Items.Add(new TextBlock().Text = "\n\n");


        }

    }

用戶控件的XAML:

<UserControl x:Class="WLive.Routenplanung"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
         xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
         xmlns:ControlsExtended="http://schemas.xceed.com/wpf/xaml/toolkit"
         xmlns:local="clr-namespace:WLive">
<UserControl.Resources>
    <local:FontSizeConverter x:Key="fontSizeCon" />
</UserControl.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="8*"/>
        <ColumnDefinition Width="92*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="11*"/>
        <RowDefinition Height="11*"/>
        <RowDefinition Height="8*" />
        <RowDefinition Height="10*"/>
        <RowDefinition Height="8*"/>
        <RowDefinition Height="52*"/>
    </Grid.RowDefinitions>
    <Label Content="Von: " Grid.Column="0" FontSize="18" Grid.Row="0" />
    <toolkit:AutoCompleteBox x:Name="tbvon" Grid.Row="0" Grid.Column="1" FilterMode="Contains" MinimumPrefixLength="4" 
             FontSize="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Converter={StaticResource fontSizeCon}}" TextChanged="routevon_TextChanged"/>
    <Label Content="Nach: " Grid.Column="0" FontSize="18" Grid.Row="1"/>
    <toolkit:AutoCompleteBox x:Name="tbnach" Grid.Row="1" Grid.Column="1" FilterMode="Contains" MinimumPrefixLength="4" 
             FontSize="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Converter={StaticResource fontSizeCon}}" TextChanged="routenach_TextChanged"/>
    <RadioButton x:Name="radioabf" Grid.Row="2" Grid.ColumnSpan="2" Content="Abfahrt" FontSize="18" IsChecked="True"/>
    <RadioButton x:Name="radioank" Grid.Row="2" Grid.ColumnSpan="2" Content="Ankunft" FontSize="18" Margin="100 0 0 0"/>
    <StackPanel Grid.Row="3" Grid.ColumnSpan="2">
        <ControlsExtended:DateTimePicker x:Name="datumsscheisse"></ControlsExtended:DateTimePicker>
    </StackPanel>
    <Button x:Name="butabfragen" Grid.Row="4" Grid.ColumnSpan="2" FontSize="18" Content="Route berechnen" HorizontalAlignment="Right" Click="abfragen_Click" />
    <ListBox x:Name="box" Grid.Row="5" Grid.ColumnSpan="2">
    </ListBox>

</Grid>

routenplanungSelection文件背后的代碼

        private string datum;

    public string Datum
    {
        get { return datum; }
        set { datum = value; }
    }
    private string zeit;

    public string Zeit
    {
        get { return zeit; }
        set { zeit = value; }
    }
    private bool abfahrt;

    public bool Abfahrt
    {
        get { return abfahrt; }
        set { abfahrt = value; }
    }



    public RoutenplanungSelection()
    {
        InitializeComponent();
    }

    public void uebergebeXmlOrigins(XElement xml)
    {

        var getAllOrigins = from a in xml.Descendants("odvNameElem")
                            select new
                            {
                                id = a.Attribute("id").Value,
                                name = a.Value
                            };

        foreach (var r in getAllOrigins)
        {
            comboabfahrt.ItemsSource = getAllOrigins;
        }
    }


    public void uebergebeXmlDestination(XElement xml)
    {

        var getAllDestinations = from a in xml.Descendants("odvNameElem")
                                 select new
                                 {
                                     id = a.Attribute("id").Value,
                                     name = a.Value
                                 };

        foreach (var r in getAllDestinations)
        {
            comboziel.ItemsSource = getAllDestinations;
        }
    }




    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string abfahrtid = comboabfahrt.SelectedValue.ToString();
        string zielid = comboziel.SelectedValue.ToString();


        new Routenplanung().downloadEindeutigenXml(abfahrtid, zielid, Datum, Zeit, Abfahrt);


    }

    public void uebergebeAllgemeineInfos(string datum, string zeit, bool abfahrt)
    {
        Datum = datum;
        Zeit = zeit;
        Abfahrt = abfahrt;
    }

窗口的XAML:

<Controls:MetroWindow x:Class="WLive.RoutenplanungSelection"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
    Title="WLive - Routenplanung, Haltestellenspezifikation" Height="230" Width="400" MinHeight="230" MinWidth="400">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="15*"/>
        <ColumnDefinition Width="85*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <Label Content="Bitte spezifizieren Sie Ihre Eingaben:" FontSize="18" Foreground="Red" FontWeight="Bold" Grid.Row="0" Grid.Column="1"/>
    <Label Content="Von:" Grid.Column="0" Grid.Row="1" FontSize="24" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
    <Label Content="Nach:" Grid.Column="0" Grid.Row="2" FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
    <ComboBox x:Name="comboabfahrt" Grid.Column="1" Grid.Row="1" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
    <ComboBox x:Name="comboziel" Grid.Column="1" Grid.Row="2" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
    <Button Grid.Row="3" Margin="0 5 5 5" HorizontalAlignment="Right" FontSize="20" Grid.Column="1" Click="Button_Click">OK</Button>
</Grid>

我的目標是,如果出現新窗口,我指定了我的電台,請單擊“確定”,該窗口將關閉,並在列表框中顯示結果。 一切正常,因為如果我說MessageBox.Show(xml.ToString()); 在formatData(XElement xml)方法中,它向我顯示了正確的xml文件...但是它沒有出現在列表框中。

看一看RoutenplanungSelection窗口的Button_Click方法:首先檢索幾個選定的值,然后創建一個 Routenplanung窗口的新實例

當然,新實例與您在屏幕上看到的主窗口不是同一實例。 在輔助窗口中,您應該參考主窗口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM