从C#解决方案中的控制台应用程序执行WPF

本文关键字:应用程序 执行 WPF 控制台 解决方案 | 更新日期: 2023-09-27 18:21:47

我正试图从VS2012中同一解决方案中构建的控制台应用程序中执行WPF类库。我已经确定,在我第一次遇到这个错误后,我需要这样做

输出类型为类库的项目不能直接启动。为了调试此项目,请在此解决方案中添加一个引用库项目的可执行项目。将可执行项目设置为启动项目。

这时我添加了另一个控制台项目,并添加了初始WPF作为控制台应用程序的参考。我还右键单击了解决方案>属性>启动项目>我选择了控制台项目并选中了"单一启动项目"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Interfaces.Connection;
namespace API
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Do I need to do something in here to call the initializecomponent() method from the WPF project???");
        Console.ReadLine();            
    }
}

}

正如代码writeLine所说,我需要在程序中的Main()方法中做些什么吗。控制台应用程序的Cs来调用初始化组件或该WPF中的某些东西??因为当我在Main()完全为空的情况下运行解决方案时,它似乎只是运行控制台应用程序。它打开和关闭命令行的速度非常快。

如果您需要,下面是WPF项目的所有代码。

客户端.cs

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Interfaces.Connection.ApplicationService;
namespace Interfaces.Connection
{
/// <summary>
/// This class is used to operate on the  web service.
/// </summary>
public class Client
{
    public ApplicationServiceClient Client { get; private set; }
    public string Username { get; set; }
    public string Context { get; set; }
    public string Password { get; set; }
    /// <summary>
    /// Initializes a new instance of the <see cref="Client"/> class.
    /// </summary>
    /// <param name="client">The client.</param>
    public Client(ApplicationServiceClient client)
    {
        Client = client;
    }
    /// <summary>
    /// Pings the web service.
    /// </summary>
    /// <returns></returns>
    public bool Ping()
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            PingResponse pingResponse = (PingResponse)Client.Run(new PingRequest());
            return pingResponse != null;
        }
    }
    /// <summary>
    /// Creates an instance of a given entity.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="pivotMember">The pivot member.</param>
    /// <param name="parent">The parent.</param>
    /// <returns></returns>
    public Instance Create(string entityName, Guid? pivotMember, ParentReference parent)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.Create(entityName, pivotMember, parent);
        }
    }
    /// <summary>
    /// Saves the specified instance.
    /// </summary>
    /// <param name="instance">The instance.</param>
    public void Save(Instance instance)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            Client.Save(instance);
        }
    }
    /// <summary>
    /// Deletes the instance with the specified primary key.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="id">The id.</param>
    public void Delete(string entityName, Guid id)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            Client.Delete(entityName, id);
        }
    }
    /// <summary>
    /// Selects an instance by its primary key.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="id">The id.</param>
    /// <returns></returns>
    public Instance SelectById(string entityName, Guid id)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.SelectById(entityName, id);
        }
    }
    /// <summary>
    /// Executes the given QueryBase and returns the result.
    /// </summary>
    /// <param name="query">The query.</param>
    /// <returns></returns>
    public QueryResult SelectByQuery(QueryBase query)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.SelectByQuery(query);
        }
    }
    private void AddCredentials()
    {
        const string contextNamespace = "http://.com/2011/servicecontracts/headers";
        const string contextName = "ContextualPerspective";
        const string userNameHeaderName = "UserName";
        const string passwordHeaderName = "Password";
        MessageHeader activeMember = MessageHeader.CreateHeader(contextName, contextNamespace, Context);
        OperationContext.Current.OutgoingMessageHeaders.Add(activeMember);
        MessageHeader userNameHeader = MessageHeader.CreateHeader(userNameHeaderName, contextNamespace, Username);
        OperationContext.Current.OutgoingMessageHeaders.Add(userNameHeader);
        MessageHeader userPasswordHeader = MessageHeader.CreateHeader(passwordHeaderName, contextNamespace, Password);
        OperationContext.Current.OutgoingMessageHeaders.Add(userPasswordHeader);
    }
}
}

主窗口XAML(这是窗口)

<Window x:Class="Interfaces.Connection.ConnectionDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="API Connector" Height="Auto" Width="525">
<Grid Background="#F0F0F0">
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Margin" Value="10,10,5,5"/>
        </Style>
        <Style TargetType="Button">
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Height" Value="26"/>
            <Setter Property="Width" Value="100"/>
        </Style>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Varasset Server Url" />
    <TextBox x:Name="txtVarassetServer" Grid.Column="1" Margin="5,10,10,5" />
    <TextBlock Grid.Row="1" Text="Username" />
    <TextBox x:Name="txtUsername" Grid.Row="1" Grid.Column="1" Margin="5,5,10,5" />
    <TextBlock Grid.Row="2" Text="Member Code" />
    <TextBox x:Name="txtContext" Grid.Row="2" Grid.Column="1" Margin="5,5,10,5" />
    <TextBlock Grid.Row="3" Text="Password" />
    <PasswordBox x:Name="txtPassword" Grid.Row="3" Grid.Column="1" Margin="5,5,10,5" />
    <Border Grid.Row="4" Grid.ColumnSpan="2" Margin="10,10,10,0" Height="1" BorderBrush="Gray" BorderThickness="0,1,0,0"/>
    <StackPanel Grid.Row="5" Grid.Column="1" Orientation="Horizontal" Margin="10"
                HorizontalAlignment="Right" VerticalAlignment="Bottom">
        <Button x:Name="btnOk"  Click="btnOk_Click">OK</Button>
        <Button x:Name="btnCancel" Margin="10,0,0,0" Click="btnCancel_Click">Cancel</Button>
    </StackPanel>
</Grid>

MainWindowxaml.cs(其cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.SqlServer.Dts.Runtime.Design;
using Microsoft.SqlServer.Dts.Runtime;
namespace Interfaces.Connection
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ConnectionDialog : Window
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ConnectionDialog"/> class.
    /// </summary>
    /// <param name="context">The context.</param>
    public ConnectionDialog(ConnectionManagerUI context)
    {
        InitializeComponent();
        DataContext = context;
        txtPassword.Password = context.Password;
        txtUsername.Text = context.Username;
        txtContext.Text = context.Context;
        txtServer.Text = context.Address;
    }
    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        ConnectionManagerUI manager = ((ConnectionManagerUI)DataContext);
        manager.Password = txtPassword.Password;
        manager.Username = txtUsername.Text;
        manager.Context = txtContext.Text;
        manager.Address = txtServer.Text;
        Close();
    }
    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}
}

还有几个文件,但我认为它们在这一点上不相关。

我也尝试过像这样从main调用initializeComponent。

Interfaces.Connection.ConnectionDialog app = new Interfaces.Connection.ConnectionDialog();
app.InitializeComponent();

但它随后给出错误,称

Interfaces.Connection.ConnectionDialog"不包含接受0个参数的构造函数。

我不确定它会引发什么样的争论。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime.Design;
using Microsoft.SqlServer.Dts.Runtime;
namespace Interfaces.Connection
{
/// <summary>
/// This class extends the class Microsoft.SqlServer.Dts.Runtime.Design.IDtsConnectionManagerUI.
/// </summary>
public class ConnectionManagerUI : IDtsConnectionManagerUI
{
    private ConnectionManager _connectionManager;
    private IServiceProvider _serviceProvider;
    /// <summary>
    /// Gets or sets the username.
    /// </summary>
    /// <value>
    /// The username.
    /// </value>
    public string Username
    {
        get
        {
            var property = _connectionManager.Properties["Username"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Username"].SetValue(_connectionManager, value); }
    }
    /// <summary>
    /// Gets or sets the context (member code).
    /// </summary>
    /// <value>
    /// The context.
    /// </value>
    public string Context
    {
        get
        {
            var property = _connectionManager.Properties["Context"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Context"].SetValue(_connectionManager, value); }
    }
    /// <summary>
    /// Gets or sets the password.
    /// </summary>
    /// <value>
    /// The password.
    /// </value>
    public string Password
    {
        get 
        {
            var property = _connectionManager.Properties["Password"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Password"].SetValue(_connectionManager, value); }
    }
    /// <summary>
    /// Gets or sets the address.
    /// </summary>
    /// <value>
    /// The address.
    /// </value>
    public string Address
    {
        get
        {
            var property = _connectionManager.Properties["Address"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Address"].SetValue(_connectionManager, value); }
    }
    /// <summary>
    /// Method not implemented.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    public void Delete(System.Windows.Forms.IWin32Window parentWindow)
    {
        throw new NotImplementedException("Delete");
    }
    /// <summary>
    /// Edits an existing connection manager.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    /// <param name="connections">The connections available for editing.</param>
    /// <param name="connectionUIArg">A class that implements the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.ConnectionManagerUIArgs"/>, such as the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.FileConnectionManagerUIArgs"/> or <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.MultiFileConnectionManagerUIArgs"/>.</param>
    /// <returns>
    /// true if the connection manager was modified.
    /// </returns>
    public bool Edit(System.Windows.Forms.IWin32Window parentWindow, Microsoft.SqlServer.Dts.Runtime.Connections connections, ConnectionManagerUIArgs connectionUIArg)
    {
        return new ConnectionDialog(this).ShowDialog().GetValueOrDefault();
    }
    /// <summary>
    /// Initializes the connection manager user interface. This method is called when you need to create connections of a specific type.
    /// </summary>
    /// <param name="connectionManager">The connection manager to initialize.</param>
    /// <param name="serviceProvider">The object used to get registered services. Defines a mechanism for retrieving services offered by the designer for such activities as monitoring changes to components.</param>
    public void Initialize(Microsoft.SqlServer.Dts.Runtime.ConnectionManager connectionManager, IServiceProvider serviceProvider)
    {
        _connectionManager = connectionManager;
        _serviceProvider = serviceProvider;
    }
    /// <summary>
    /// Provides notification to tasks of newly created connection managers. This method is called after a new connection manager is added to the package.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    /// <param name="connections">The connections collection to add the new connection to, or the connections to show in a drop-down or other control in the user interface.</param>
    /// <param name="connectionUIArg">A class that implements the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.ConnectionManagerUIArgs"/>, such as the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.FileConnectionManagerUIArgs"/> or <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.MultiFileConnectionManagerUIArgs"/>.</param>
    /// <returns>
    /// true if a new connection was created.
    /// </returns>
    public bool New(System.Windows.Forms.IWin32Window parentWindow, Microsoft.SqlServer.Dts.Runtime.Connections connections, ConnectionManagerUIArgs connectionUIArg)
    {
        return new ConnectionDialog(this).ShowDialog().GetValueOrDefault();
    }
}
}

提前感谢!

编辑我已将program.cs Main()方法更改为:

class Program
{
    static void Main(string[] args)
    {
        ConnectionManagerUI connectionManagerUI = new ConnectionManagerUI;
        ConnectionDialog dialog = new ConnectionDialog(ConnectionManagerUI);          
    }
}

它现在运行,但它给出错误

PresentationCore.dll中发生类型为"System.InvalidOperationException"的未处理异常附加信息:调用线程必须是STA,因为许多UI组件都需要它。

如果我需要创建一个新的帖子,或者我可以在发布之前先研究一下。但是Tim解决了这个帖子的问题。

编辑结束

从C#解决方案中的控制台应用程序执行WPF

当我们正在解决真正的问题时,我会继续说,您遇到的最后一个问题是ConnectionDialog的构造函数被定义为

public ConnectionDialog(ConnectionManagerUI context)
{
    ...
}

看看它是如何将ConnectionManagerUI对象作为参数的?我不知道那个类是什么(您没有共享那个代码),但您需要将其中一个传递到构造函数中

编辑:现在你已经添加了代码,我可以看到它有一个默认的构造函数,所以我将把代码改为:

ConnectionManagerUI connectionManagerUI = new ConnectionManagerUI();
ConnectionDialog dialog = new ConnectionDialog(connectionManagerUI);

另外,不要在对话框上调用.InitializeComponent()。它实际上应该只从构造函数(它就是构造函数)调用。叫两次就不好了。

也就是说,这并不能解决你的根本问题,那就是你似乎只想做一个WPF应用程序:)

编辑:不过,就像我说的,这不是你的根本问题。除非迫不得已,否则你不应该这样做,我怀疑你是否必须这样做。