[英]Converting a Hex String (from WPF TextBox) into byte
我編寫小型WPF應用程序。 在我的應用程序中,我有一個名為Seq
字段,它實際上是字節數據。
因此,應該通過WPF應用程序的TextBox
更新Seq
字段。 但是文本字符串將以十六進制格式鍵入,且不以0x開頭。
基本上,我需要寫下算法以完成Seq
的set方法,以僅設置一個字節的數據。
通過文本框更新的對象類:
public class WProtocol {
private byte _seq
public byte Seq {
get {
return _seq;
}
set {
_seq = value;
}
}
}
WFrameWindow.xaml.cs
:
public partial class WFrameWindow: Window {
WProtocol m_WProtocol = new WProtocol();
public WFrameWindow() {
InitializeComponent();
this.DataContext = m_WProtocol;
}
}
WFrameWindow.xaml
代碼片段,用於顯示源代碼的綁定:
<TextBox HorizontalAlignment="Left" Height="24" Margin="115,26,0,0" TextWrapping="Wrap" Text="{***Binding Seq,Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged***}" VerticalAlignment="Top" Width="99" FontSize="9" FontFamily="Arial"/>
您的解決方案是;
private string _seq_string;
public string SeqString
{
get { return _seq_string; }
set
{
_seq_string = value;
SeqBytes = StringToByteArray(value);
}
}
public byte[] SeqBytes { get; set; }
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
和XAML代碼將是:
<TextBox HorizontalAlignment="Left" Height="24" Margin="115,26,0,0" TextWrapping="Wrap" Text="{***Binding SeqString,Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged***}" VerticalAlignment="Top" Width="99" FontSize="9" FontFamily="Arial"/>
我建議的答案是使用轉換器而不是ViewModel中的代碼:
XamlCode:
<TextBox HorizontalAlignment="Left" Height="24" Margin="115,26,0,0" TextWrapping="Wrap"
Text="{Binding Seq, Converter={StaticResource StringToByteConverter}, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Top" Width="99" FontSize="9" FontFamily="Arial"/>
轉換器:
class StringToByteConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is String)
{
string valueTyped = (String)value;
if (String.IsNullOrEmpty(valueTyped) == false && valueTyped.Length <= 2)
return System.Convert.ToByte(valueTyped, 16);
}
return new byte();
}
}
要使用轉換器,請將其添加到參考資料中:
...
xmlns:local="clr-namespace:MyProject"
...
<Application.Resources>
<local:StringToByteConverter x:Key="StringToByteConverter"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.