[英]how do I access a XAML object from a class other than main?
如果我嘗試“var mainpage new Mainpage()”,我將運行主頁構造函數,然后 XAML object 中的所有字段將返回到 null。 如何訪問 silverlight 中來自不同 class 但屬於同一命名空間的 XAML 對象?
讓我舉例說明。 如果您查看第一個答案,這就是我遇到的
public class MyPage
{
MyPage()
{
// the constructor makes all the variables from the xaml null
}
public TextBox MyTextBox
{
get { return SomeTextBox; }
}
}
public class SomeOtherClass
{
private void SomeFunction()
{
var page = new MyPage(); // this makes the text empty
var sometext = page.MyTextBox.Text; // so sometext will be empty
}
}
因此,當我運行 SomeFunction 時,無論用戶在程序首次運行時輸入的內容都會變成 null。
我首先要嘗試的是查看是否在創建 SomeClass 時將值放入該 class 中。
如果失敗,我將嘗試 MVVM。 我看過http://www.vimeo.com/8915487視頻,我得到了示例 mvvm 代碼
這是 Model:
namespace SimpleMVVM.Model
{
public class SimpleModel
{
// super easy version
//public string SomeSimpleValue { get; set; }
private string _SomeSimpleValue = string.Empty;
// actually do something version...
public string SomeSimpleValue
{
get
{
return "some value";
}
set
{
_SomeSimpleValue = value;
}
}
}
}
這是視圖:
這是viewmodel.cs
using Simple;
using SimpleMVVM.Model;
namespace SimpleMVVM.ViewModel
{
public class SimpleViewModel : SimpleViewModelBase
{
private SimpleModel MyModel = new SimpleModel();
public string SomeSimpleValue
{
get { return MyModel.SomeSimpleValue; }
set
{
if (MyModel.SomeSimpleValue != value)
{
MyModel.SomeSimpleValue = value;
RaisePropertyChanged("SomeSimpleValue");
}
}
}
}
}
使用這個例子,我想知道它是否像注入 ViewModel 然后更改 Model 和 View 中的綁定一樣簡單。
MVVM 真的這么簡單嗎?
還有一個。 它是viewmodel基礎class
using System.ComponentModel;
namespace Simple
{
public class SimpleViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string PropertyName)
{
var e = new PropertyChangedEventArgs(PropertyName);
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}
}
好的,現在是困難的部分。 如果我創建一個新的 class。 如何從視圖模型 class 獲取數據?
首先,讓我擺脫這種咆哮:您提出的設計非常糟糕。 它符合臭代碼的定義。
如果您堅持這樣做,“最佳”方法是在您的頁面上聲明一些返回實際 UI 元素的公共變量。
<UserControl x:Class="MyNamespace.MyPage" ...>
<Grid>
<TextBox x:Name="SomeTextBox" Width="100" />
</Grid>
</UserControl>
public class MyPage
{
public TextBox MyTextBox
{
get { return SomeTextBox; }
}
}
public class SomeOtherClass
{
private void SomeFunction()
{
var page = new MyPage();
page.MyTextBox.Text = "some text";
}
}
當然首選的方法是使用類似 MVVM 模式的東西來實現從 window 到它的視圖模型的綁定,然后你可以從視圖模型中讀取屬性值,這樣你就可以避免嘗試從完全不同的地方觸摸任何 UI 元素class。
另一種方法(不走完整的 MVVM 路線)是將必要的值注入到您正在實例化的控件/頁面的構造函數中,然后您可以從那里將它們分配給適當的 UI 元素屬性。 這仍然很臭,但比直接從外部訪問 UI 元素要好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.