将字符串属性绑定到状态栏文本

时间:2014-02-12 14:11:27

标签: c# wpf data-binding

我尝试绑定字符串属性,以便在我的状态栏中显示我的数据库是否已连接。这是代码:

C#

public class TimeBase : INotifyPropertyChanged
{
    private DXTickDB db;
    string[] args = new string[] { };

    public event PropertyChangedEventHandler PropertyChanged;
    private bool isTBconnected;
    public string connectionStatus { get; set; }

    public bool tb_isconnected
    {
        get { return isTBconnected; }
        set
        {
            if (value != isTBconnected)
            {
                isTBconnected = value;

                if(isTBconnected == false)
                {
                    connectionStatus = "TimeBase is not connected";
                }
                else
                {
                    connectionStatus = "TimeBase is connected";
                }

                OnPropertyChanged("connectionStatus");
            }
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }


    #region TimeBase Connection

    public void ConnectToTimeBase()
    {
        if (args.Length == 0)
            args = new string[] { "not available for security reasons" };

        db = TickDBFactory.createFromUrl(args[0]);
        try
        {
            db.open(true);
            tb_isconnected = true;
        }
        catch
        {
            tb_isconnected = false;
        }

    }
    #endregion

这是我主窗口中状态栏的Xaml:

        <StatusBar Height="23" DockPanel.Dock="Bottom" Background="Green">
        <StatusBarItem>
            <StackPanel Orientation="Horizontal">
                <TextBlock 
                    Foreground="{StaticResource Foreground}"
                    Text="{Binding Path=connectionStatus}"> 
                </TextBlock>
            </StackPanel>
        </StatusBarItem>
    </StatusBar>

我试图将它绑定到字符串属性connectionStatus但是没有文本出现,即使我调试它时我可以看到connectionStatus已更新。对这里的错误有任何建议吗?

1 个答案:

答案 0 :(得分:2)

DataContext属性应包含您的模型,如下所示:

 TimeBase timeBaseInstance;
    public MainWindow()
    {
        timeBaseInstance = new TimeBase();

        //Set the dataContext so bindings can iteract with your data
        DataContext = timeBaseInstance;
        InitializeComponent();
    }