C#WPF从窗口中的用户控件调用方法

时间:2015-03-22 18:20:18

标签: c# wpf xaml user-controls listbox

我有一个很大的问题.... 我有一个MainWindow.xaml。这个xaml分成不同的列和行。在左侧,我有不同的按钮。在右侧,我有我所谓的内容网格。在此内容网格中,我可以通过按下按钮打开不同的用户控件。

在其中一个用户控件中,我请求从A到B的路线。如果点被激烈地识别,路线将显示在输入屏幕下方的列表框中。

但如果两点中的一点未被准确识别,我打开一个带有两个组合框的新窗口,您必须指定并选择输入。选择起点和终点后。按下OK按钮关闭窗口,在用户控件的列表框中显示路径......但是它没有......

我的英语不是那么好,我希望你可以通过发布代码帮助我..

用户控件的代码隐藏文件:

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文件......但它并没有出现在列表框中....

1 个答案:

答案 0 :(得分:0)

查看Button_Click窗口的RoutenplanungSelection方法:首先检索几个选定的值,然后 创建新实例 Routenplanung窗口。

当然,新实例与您在屏幕上看到的主窗口的实例不同。在辅助窗口中,您应该引用主要窗口。