我有我的自定義控件MyControl,它具有公共方法Start()。如何在不使用x的情況下在自定義控件中使用公共方法:名稱
public partial class MyControl : UserControl
{
// This must be private.
private int _idNumber;
public MyControl()
{
InitializeComponent();
}
public void Start(int idNumber)
{
_idNumber = idNumber;
}
}
在MainWindow中,我將一個MyControl與x:Name =「myControl」放在一起。
<Window x:Class="MyNameSpace.MainWindow"
xmlns:local="clr-namespace:MyNameSpace">
<Grid>
<local:MyControl x:Name="myControl"/>
</Grid>
</Window>
在MainWindow的Start方法中,我使用x:Name調用MyControl的Start方法。
public partial class MainWindow : Window
{
// This must be private
private int _myContolId;
public MainWindow()
{
InitializeComponent();
}
public void Start()
{
// ID must be set here.
_myControlId = 1;
myControl.Start(_myControlId);
}
}
如何在不使用x:Name的情況下做同樣的事情?
請注意,MyControl的加載事件在我的情況下是無效的,因爲MyControl的Start()方法必須在作爲可視元素加載之前調用。
由於必須在MainWindow的Start方法中設置int參數idNumber,所以在MyControl的構造函數或初始化時調用Start也是無效的。
更重要的是,MainControlow的_ControlNumber和_myContolId對於setter和getter都必須是私有的。
調用在MyControl的構造函數中開始?或者在重載的OnInitialized方法中? – Clemens
@Clemens感謝您的快速回復,但這是不可能的。我在我的問題的編輯版本中解釋了我真正想做的事情。 – user4134476