Существует ли Silverlight-эквивалент «Application.OpenForms»? - PullRequest
2 голосов
/ 18 мая 2010

По сути, я пытаюсь взять информацию, введенную пользователем на одной странице, и распечатать ее на другой странице с помощью «печатной» версии или отчета о чем-либо. У меня есть MainPage.xaml, который, как следует из названия, является моей главной страницей, но в окне есть подстраница AdCalculator.xaml, где пользователь вводит информацию, и PrintEstimate.xaml, к которой осуществляется переход с помощью кнопки на AdCalculator.

Я хотел бы иметь возможность передавать информацию, введенную в текстовые поля, из AdCalculator и распечатывать ее через текстовые блоки в PrintEstimate. Поэтому для этого у меня есть следующий код:

        Views.AdCalculator AdCalc = new Views.AdCalculator();
        string PrintCompanyName = AdCalc.CompanyName;
        string PrintContactName = AdCalc.txt_CustomerName.Text;
        string PrintBillingAddress1 = AdCalc.txt_BillingAddress.Text;
        string PrintBillingAddress2 = AdCalc.txt_BillingAddressLine2.Text;
        string PrintPhoneNumber = AdCalc.txt_PhoneNumber.Text;
        string PrintNumOfAds = AdCalc.txt_NumofAds.Text;
        string PrintRateOfPlay = AdCalc.Cmb_Rate.SelectedValue.ToString();
        string PrintNumOfMonths = AdCalc.txt_NumofMonths.Text;
        string PrintTotalDue = AdCalc.txt_InvoiceSummary_TotalDue.Text;

        PrintEstimate PrintEstimatePage = new PrintEstimate();
        PrintEstimatePage.txt_CompanyName.Text = PrintCompanyName;
        PrintEstimatePage.txt_CustomerName.Text = PrintContactName;
        PrintEstimatePage.txt_BillingAddress.Text = PrintBillingAddress1;
        PrintEstimatePage.txt_BillingAddressLine2.Text = PrintBillingAddress2;
        PrintEstimatePage.txt_PhoneNumber.Text = PrintPhoneNumber;
        PrintEstimatePage.txt_InvoiceSummary_NumofAds.Text = PrintNumOfAds;
        PrintEstimatePage.txt_InvoiceSummary_RateofPlay.Text = PrintRateOfPlay;
        PrintEstimatePage.txt_InvoiceSummary_NumOfMonths.Text = PrintNumOfMonths;
        PrintEstimatePage.txt_EstimateTotal.Text = PrintTotalDue;

Единственная проблема в том, что когда я создаю новую страницу AdCalculator, она очищает значения, поэтому на самом деле ничего не сохраняется, пока идет ввод данных пользователем. Следуя указаниям коллеги, я считаю, что все, что мне нужно сделать, это изменить линию

        Views.AdCalculator AdCalc = new Views.AdCalculator();

до

        Views.AdCalculator AdCalc = (AdCalculator)Application.OpenForms["AdCalculator"]; 

за исключением "Apllication.OpenForms" не регистрируется. Я знаю, что существует много различий в том, как выделен код C # для приложений Silverlight, поэтому я не знал, есть ли какой-нибудь эквивалент, который кто-либо знал о «Application.OpenForms», который помог бы решить мою проблему или если бы был какой-то другой способ выполнить мою задачу.

1 Ответ

2 голосов
/ 19 мая 2010

Если я правильно понимаю ваш вопрос, вы просто хотите получить пользовательский ввод и отобразить его.

Я предлагаю вам начать с определения класса, который будет представлять вводимые вами данные, например:

public class Customer
{
    public string ContectName { get; set; }
    public string BillingAddress1 { get; set; }
    public string BillingAddress2 { get; set; }
    public string PhoneNumber { get; set; }
    public int NumOfAds { get; set; }
    public double RateOfPlay { get; set; }
    public int NumOfMonths { get; set; }
    public double TotalDue { get; set; }
}

На странице, где пользователь вводит данные, вы затем создаете экземпляр этого класса, либо путем создания экземпляра вручную и настройки его свойства при отправке пользователем (аналогично тому, что вы делаете в своем коде) или используйте привязку данных в ваших интересах (это то, что я предпочитаю).

Допустим, например, что вы вводите данные на главной странице

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    this.DataContext = new Customer();
}

Теперь вы можете связать элементы управления. Допустим, вы используете сетку:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <sdk:Label Content="Billing Address 1:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress1TextBox" Text="{Binding Path=BillingAddress1, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Billing Address 2:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress2TextBox" Text="{Binding Path=BillingAddress2, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Contect Name:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="3" Name="contectNameTextBox" Text="{Binding Path=ContectName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Num Of Ads:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="numOfAdsTextBox" Text="{Binding Path=NumOfAds, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Num Of Months:" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="3" Name="numOfMonthsTextBox" Text="{Binding Path=NumOfMonths, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Phone Number:" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="5" Height="23" HorizontalAlignment="Left" Margin="3" Name="phoneNumberTextBox" Text="{Binding Path=PhoneNumber, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Rate Of Play:" Grid.Column="0" Grid.Row="6" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="6" Height="23" HorizontalAlignment="Left" Margin="3" Name="rateOfPlayTextBox" Text="{Binding Path=RateOfPlay, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
        <sdk:Label Content="Total Due:" Grid.Column="0" Grid.Row="7" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
        <TextBox Grid.Column="1" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="3" Name="totalDueTextBox" Text="{Binding Path=TotalDue, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
    </Grid>
</Grid>

Когда пользователь нажимает кнопку отправки, вы можете использовать что-то вроде этого:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var currentCustomer = this.DataContext as Customer;
    var previewWindow = new PrintPreviewWindow(currentCustomer);
    previewWindow.Show();
}

Чтобы это работало, у вас должно быть Silverlight ChildWindow, например:

public partial class PrintPreviewWindow : ChildWindow
{
    public PrintPreviewWindow(Customer customer)
    {
        InitializeComponent();
        this.DataContext = customer;
    }

    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;
    }
}

Таким образом, ваша MainPage создает новый экземпляр PrintPreviewChildWindow (может быть также страницей, если вы предпочитаете) и передает экземпляр клиента. Затем ChildWindow может делать с ним все, что захочет. Когда ChildWindow закрывается, вы, вероятно, захотите очистить страницу ввода, вы можете сделать это, просто заново установив контекст данных:

this.DataContext = new Customer();

Полагаю, это то, что вы ищете.

Постарайтесь разобраться во всем, что связано с привязкой данных, это сэкономит вам много-много строк кода И дайте нам знать, если это отвечает на ваш вопрос или если у вас есть больше: -)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...