Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将文本框绑定到类属性_C#_Wpf_Binding - Fatal编程技术网

C# 如何将文本框绑定到类属性

C# 如何将文本框绑定到类属性,c#,wpf,binding,C#,Wpf,Binding,我想将类中的属性单向绑定到文本框。但是有一个问题,场景在我下面的代码中,将test_string的字符串值放到我的视图中。这个代码我试过了,但似乎不起作用。我需要做什么 具有属性的类: namespace config { class tester : INotifyPropertyChanged { public tester() { } private string test_string;

我想将类中的属性单向绑定到文本框。但是有一个问题,场景在我下面的代码中,将test_string的字符串值放到我的视图中。这个代码我试过了,但似乎不起作用。我需要做什么

具有属性的类:

namespace config
{
    class tester : INotifyPropertyChanged
    {
        public tester()
        {
        }

        private string test_string;

        public string Test{
            get { return test_string; }
            private set
            {
                test_string = value;
                RaisePropertyChanged("Test");
            }
        }

        public void dotest(){
            ... do some testing
            Test = "Past point one"
            ... do some more testing
            Test += "Past point two"
            ... do some more testing
            Test += "Finished testing"
        }
    }
}
视图模型

using config
namespace notif
{
    class t_viewmodel
    {
        public t_viewmodel()
        {
        }

        Tester tester = new Tester();

        public string TestLink
        {
            get { return tester.Test; }
        }

        public void run_test()
        {
            tester.dotest();
        }
    }
}
看法



[EDIT1] 由于进程是通过dotest运行的,所以直到完成后才会填充文本框,是否可以在每次设置Test属性时进行此更新


[EDIT2]更改

public void SQLDBAccessTest(string db)
{
    if (test_debug)
        ConnectionTest = "Test started. " + DateTime.Now;

    string conn_string = "";

    try
    {
        conn_string = createConnectionString(db);
        if (test_debug)
            ConnectionTest += "\nConnection string = '" + conn_string + "'";
    }
    catch (Exception ex)
    {
        throw ex;
    }

    try
    {
        if (test_debug)
            ConnectionTest += "\nCreating connection to database...";

        cnn = new SqlConnection(conn_string);

        if (test_debug)
            ConnectionTest += "\nConnection created.";

        if (test_debug)
            ConnectionTest += "\nEstablishing open connection to database...";

        cnn.Open();

        if (test_debug)
            ConnectionTest += "\nEstablished connection to database.";
        if (test_debug)
            ConnectionTest += "\nClosing connection to database...";

        cnn.Close();

        if (test_debug)
            ConnectionTest += "\nConnection closed.";
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nAn error has occured whilst connecting to the database.\n\t - " + ex.Message;

        throw ex;
    }

    if (test_debug)
        ConnectionTest += "\nTest complete. " + DateTime.Now;
}

private string createConnectionString(string db)
{
    string tempConString = ConStr;

    try
    {
        TestConnSettingsFile();
        setDBDataSourceAndSecurity();

        if (test_debug)
            ConnectionTest += "\nCreating connection string...";

        tempConString = tempConString.Replace("<SERVER>", db_datasource);
        tempConString = tempConString.Replace("<DB>", db);
        tempConString = tempConString.Replace("<SECURITY>", db_security);

        if (test_debug)
            ConnectionTest += "\nCreated connection string.";
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return tempConString;
}

private bool TestConnSettingsFile()
{
    bool settingsFileExist = false;
    string filePath = "";

    if (test_debug)
        ConnectionTest += "\nTesting for encrypted connection file...";

    try
    {
        string directory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
        filePath = System.IO.Path.Combine(directory, "afx.settings");

        if (System.IO.File.Exists(filePath))
        {
            settingsFileExist = true;
            xmlSettingsFilePath = filePath;

            if (test_debug)
                ConnectionTest += "\nThe encrypted connection file has been found at: " + filePath;
        }
        else
        {
            if (test_debug)
                ConnectionTest += "\nThe encrypted connection file could not be found at: " + filePath;
            throw new Exception("The encrypted connection file could not be found at: " + filePath);
        }
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nError occured while testing if encrypted file exists:\n\t - " + ex.Message;
        throw ex;
    }

    return settingsFileExist;
}

private bool setDBDataSourceAndSecurity()
{
    bool result = false;

    if (test_debug)
        ConnectionTest += "\nRetrieving encrypted connection...";

    try
    {
        if (System.IO.File.Exists(xmlSettingsFilePath))
        {
            XmlTextReader reader = null;

            if (test_debug)
                ConnectionTest += "\nReading connection xml file...";

            // Load the file with an XmlTextReader
            reader = new XmlTextReader(xmlSettingsFilePath);
            // Read the File
            while (reader.Read())
            {
                //checking where read text is element and and name is “DataSource”
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "DataSource")
                {
                    if (test_debug)
                        ConnectionTest += "\nReading data source...";

                    //assigning ReadElementstring to strCmb1.
                    string datasource = reader.ReadElementString();

                    if (test_debug)
                        ConnectionTest += "\nData source = " + db_datasource;
                }
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Security")
                {
                    if (test_debug)
                        ConnectionTest += "\nReading security...";

                    string security = reader.ReadElementString();

                    if (test_debug)
                        ConnectionTest += "\nSecurity = " + db_security;
                }
            }
            if (test_debug)
                ConnectionTest += "\nClosing connection xml file...";

            reader.Close();
            reader = null;

            if (test_debug)
                ConnectionTest += "\nSuccess retrieving encrypted connection...";

            result = true;
        }
        else
        {
            if (test_debug)
                ConnectionTest += "\nLost connection xml file, could not be found at: " + xmlSettingsFilePath;
            throw new Exception("The configuration file, setup for database connectivity could not be found.");
        }
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nError occured while setting data source and security:\n\t - " + ex.Message;
        throw ex;
    }
    return result;
}
public void SQLDBAccessTest(字符串db)
{
如果(测试调试)
ConnectionTest=“测试已开始。”+DateTime.Now;
字符串conn_string=“”;
尝试
{
conn_字符串=createConnectionString(db);
如果(测试调试)
ConnectionTest+=“\n连接字符串=”+“连接字符串+”;
}
捕获(例外情况除外)
{
掷骰子;
}
尝试
{
如果(测试调试)
ConnectionTest+=“\n正在创建到数据库的连接…”;
cnn=新的SqlConnection(连接字符串);
如果(测试调试)
ConnectionTest+=“\n已创建连接。”;
如果(测试调试)
ConnectionTest+=“\n正在建立与数据库的开放连接…”;
cnn.Open();
如果(测试调试)
ConnectionTest+=“\n已建立到数据库的连接。”;
如果(测试调试)
ConnectionTest+=“\n关闭与数据库的连接…”;
cnn.Close();
如果(测试调试)
ConnectionTest+=“\n连接已关闭。”;
}
捕获(例外情况除外)
{
如果(测试调试)
ConnectionTest+=“\n连接到数据库时发生错误。\n\t-”+例如消息;
掷骰子;
}
如果(测试调试)
ConnectionTest+=“\n测试完成。”+DateTime.Now;
}
私有字符串createConnectionString(字符串数据库)
{
字符串tempConString=ConStr;
尝试
{
TestConnSettingsFile();
setDBDataSourceAndSecurity();
如果(测试调试)
ConnectionTest+=“\n正在创建连接字符串…”;
tempConString=tempConString.Replace(“,db_数据源);
tempcontring=tempcontring.Replace(“,db);
tempcontring=tempcontring.Replace(“,db_security”);
如果(测试调试)
ConnectionTest+=“\n创建的连接字符串。”;
}
捕获(例外情况除外)
{
掷骰子;
}
返温;
}
私有布尔测试连接设置文件()
{
bool设置fileexist=false;
字符串filePath=“”;
如果(测试调试)
ConnectionTest+=“\n测试加密的连接文件…”;
尝试
{
string directory=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
filePath=System.IO.Path.Combine(目录“afx.settings”);
if(System.IO.File.Exists(filePath))
{
settingsFileExist=true;
xmlSettingsFilePath=filePath;
如果(测试调试)
ConnectionTest+=“\n已在以下位置找到加密的连接文件:”+文件路径;
}
其他的
{
如果(测试调试)
ConnectionTest+=“\n在以下位置找不到加密的连接文件:”+文件路径;
抛出新异常(“在“+filePath”处找不到加密的连接文件);
}
}
捕获(例外情况除外)
{
如果(测试调试)
ConnectionTest+=“\n测试加密文件是否存在时出错:\n\t-“+ex.Message;
掷骰子;
}
返回设置文件存在;
}
私有bool setDBDataSourceAndSecurity()
{
布尔结果=假;
如果(测试调试)
ConnectionTest+=“\n正在检索加密连接…”;
尝试
{
if(System.IO.File.Exists(xmlSettingsFilePath))
{
XmlTextReader=null;
如果(测试调试)
ConnectionTest+=“\n正在读取连接xml文件…”;
//使用XmlTextReader加载文件
reader=新的XmlTextReader(xmlSettingsFilePath);
//读文件
while(reader.Read())
{
//检查读取文本为元素且名称为“数据源”的位置
if(reader.NodeType==XmlNodeType.Element&&reader.Name==DataSource)
{
如果(测试调试)
ConnectionTest+=“\n正在读取数据源…”;
//将ReadElementstring分配给strCmb1。
string datasource=reader.ReadElementString();
如果(测试调试)
ConnectionTest+=“\n数据源=“+db\u数据源;
}
if(reader.NodeType==XmlNodeType.Element&&reader.Name==“安全性”)
{
如果(测试调试)
ConnectionTest+=“\n读取安全…”;
字符串安全性=reader.ReadElementString();
如果(测试调试)
ConnectionTest+=“\n安全性=“+db\U安全性;
}
}
如果(测试调试)
ConnectionTest+=“\n关闭连接xml文件…”;
reader.Close();
reader=null;
如果(测试调试)
ConnectionTest+=“\n成功检索加密连接…”;
结果=真;
}
其他的
{
如果(测试调试)
ConnectionTest+=“\n在以下位置找不到缺少连接的xml文件:”+xmlSettingsFilePath;
抛出新异常(“找不到配置文件,数据库连接设置”);
}
}
捕获(例外情况除外)
{
如果(测试调试)
连接测试+=”
public void SQLDBAccessTest(string db)
{
    if (test_debug)
        ConnectionTest = "Test started. " + DateTime.Now;

    string conn_string = "";

    try
    {
        conn_string = createConnectionString(db);
        if (test_debug)
            ConnectionTest += "\nConnection string = '" + conn_string + "'";
    }
    catch (Exception ex)
    {
        throw ex;
    }

    try
    {
        if (test_debug)
            ConnectionTest += "\nCreating connection to database...";

        cnn = new SqlConnection(conn_string);

        if (test_debug)
            ConnectionTest += "\nConnection created.";

        if (test_debug)
            ConnectionTest += "\nEstablishing open connection to database...";

        cnn.Open();

        if (test_debug)
            ConnectionTest += "\nEstablished connection to database.";
        if (test_debug)
            ConnectionTest += "\nClosing connection to database...";

        cnn.Close();

        if (test_debug)
            ConnectionTest += "\nConnection closed.";
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nAn error has occured whilst connecting to the database.\n\t - " + ex.Message;

        throw ex;
    }

    if (test_debug)
        ConnectionTest += "\nTest complete. " + DateTime.Now;
}

private string createConnectionString(string db)
{
    string tempConString = ConStr;

    try
    {
        TestConnSettingsFile();
        setDBDataSourceAndSecurity();

        if (test_debug)
            ConnectionTest += "\nCreating connection string...";

        tempConString = tempConString.Replace("<SERVER>", db_datasource);
        tempConString = tempConString.Replace("<DB>", db);
        tempConString = tempConString.Replace("<SECURITY>", db_security);

        if (test_debug)
            ConnectionTest += "\nCreated connection string.";
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return tempConString;
}

private bool TestConnSettingsFile()
{
    bool settingsFileExist = false;
    string filePath = "";

    if (test_debug)
        ConnectionTest += "\nTesting for encrypted connection file...";

    try
    {
        string directory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
        filePath = System.IO.Path.Combine(directory, "afx.settings");

        if (System.IO.File.Exists(filePath))
        {
            settingsFileExist = true;
            xmlSettingsFilePath = filePath;

            if (test_debug)
                ConnectionTest += "\nThe encrypted connection file has been found at: " + filePath;
        }
        else
        {
            if (test_debug)
                ConnectionTest += "\nThe encrypted connection file could not be found at: " + filePath;
            throw new Exception("The encrypted connection file could not be found at: " + filePath);
        }
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nError occured while testing if encrypted file exists:\n\t - " + ex.Message;
        throw ex;
    }

    return settingsFileExist;
}

private bool setDBDataSourceAndSecurity()
{
    bool result = false;

    if (test_debug)
        ConnectionTest += "\nRetrieving encrypted connection...";

    try
    {
        if (System.IO.File.Exists(xmlSettingsFilePath))
        {
            XmlTextReader reader = null;

            if (test_debug)
                ConnectionTest += "\nReading connection xml file...";

            // Load the file with an XmlTextReader
            reader = new XmlTextReader(xmlSettingsFilePath);
            // Read the File
            while (reader.Read())
            {
                //checking where read text is element and and name is “DataSource”
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "DataSource")
                {
                    if (test_debug)
                        ConnectionTest += "\nReading data source...";

                    //assigning ReadElementstring to strCmb1.
                    string datasource = reader.ReadElementString();

                    if (test_debug)
                        ConnectionTest += "\nData source = " + db_datasource;
                }
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Security")
                {
                    if (test_debug)
                        ConnectionTest += "\nReading security...";

                    string security = reader.ReadElementString();

                    if (test_debug)
                        ConnectionTest += "\nSecurity = " + db_security;
                }
            }
            if (test_debug)
                ConnectionTest += "\nClosing connection xml file...";

            reader.Close();
            reader = null;

            if (test_debug)
                ConnectionTest += "\nSuccess retrieving encrypted connection...";

            result = true;
        }
        else
        {
            if (test_debug)
                ConnectionTest += "\nLost connection xml file, could not be found at: " + xmlSettingsFilePath;
            throw new Exception("The configuration file, setup for database connectivity could not be found.");
        }
    }
    catch (Exception ex)
    {
        if (test_debug)
            ConnectionTest += "\nError occured while setting data source and security:\n\t - " + ex.Message;
        throw ex;
    }
    return result;
}
public string Tester
{
    get { return tester; }
}
<TextBox Name="txtTestMessage" Text="{Binding Tester.Test}" />
public void dotest(){
    var dummyAction = new Action( () => Thread.Sleep(1000) );
    var first = new Task(dummyAction);
    var second = new Task(dummyAction);
    var third = new Task(dummyAction);

    first.ContinueWith(task =>
    {
        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            Test = Environment.NewLine + "past point one";
        }));
        second.Start();
    });
    second.ContinueWith(task =>
    {
        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            Test += Environment.NewLine + "past point two";
        }));
        third.Start();
    });
    third.ContinueWith(task => {
        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            Test += Environment.NewLine + "Finished testing";
        }));
    });
    first.Start();
}
Tester tester = new Tester();

//Add property to return your Tester instance.
public Tester TestLink
{
    get { return tester; }
}

//In your XAML bind Test property.
<TextBox Name="txtTestMessage" Text="{Binding TestLink.Test}" />